为 sqldatareader 使用 while 循环 [英] Using while loop for sqldatareader

查看:26
本文介绍了为 sqldatareader 使用 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

handle 列等于下拉列表的值,然后将该值放入标签并显示.通过使用下面提供的代码,我不断获得 policeidfullname 的最后一行数据的结果.但是,我的表包含 2 个警察帐户,其中 handle 列等于下拉列表的值.帮帮我吧.谢谢!

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

推荐答案

您必须将值放入一个集合(列表左右)中:

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....

显示连接后的字符串:

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

这篇关于为 sqldatareader 使用 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆