Using while loop for sqldatareader

蓝咒 提交于 2021-01-27 11:42:07

问题


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();

回答1:


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);


来源:https://stackoverflow.com/questions/18093943/using-while-loop-for-sqldatareader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!