Using while loop for sqldatareader

c#, sqldatareader, while-loop

Solution

you got to put the value into a collection (list or so):

    var myData = new List<string>();
    while (dr.Read())
    {
        String policeid = dr.GetString(0);
        String fullname = dr.GetString(1);
        String result = policeid + " " + fullname;
        myData.Add(result);
    }

and then use it as you want - display the first/last/concatenated/etc....

EDIT:

display the concatenated string:

    yourLabel.Text = myData.Aggregate((x,y)=> x + "; " + y);

Problem

I trying to get both policeid and fullname from my table named PoliceAccount when the handle column equal to the value of the dropdownlist and then put the value into a label and display it. By using the code provided below I keep getting the result of the last row data of policeid and fullname. However, my table contain of 2 police account which having the column handle equal to the value of the dropdownlist. Do help me out. THANKS! ``` conn.Open(); sql = "Select policeid, fullname From PoliceAccount Where handle = '"+ ddlReportDateTime.SelectedValue +"'"; using (var cmd2 = new SqlCommand(sql, conn)) { SqlDataReader dr; dr = cmd2.ExecuteReader(); while (dr.Read()) { String policeid = dr.GetString(0); String fullname = dr.GetString(1); String result = policeid + " " + fullname; lblAssignTo.Text = result; } } conn.Close(); ```

Original source