为什么listbox2仍然是空的?

时间:2015-11-17 22:21:35

标签: c# asp.net web

  

我找不到问题出在哪里,当我把while循环作为注释工作时,在while循环之后我们无法从sqldatareader中读取更多?   listbox2仍然是空的!

public partial class exTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        string sql = "select employeeid,firstname,lastname from employees";
        SqlCommand cmd = new SqlCommand(sql, con);

        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        string item;
        ListBox1.Items.Clear();
        while (reader.Read())
        {
            item =reader.GetString(1) + reader.GetString(2);
            ListBox1.Items.Add(item);
        }
        ListBox2.DataSource = reader;
        ListBox2.DataValueField = "employeeId";
        ListBox2.DataTextField = "firstname";
        ListBox2.DataBind();
        reader.Close();
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:0)

您无法再次使用reader。 来自MSDN Doc

  

提供从SQL Server数据库中读取仅向前行的方法。

您可以一次阅读一行,但是一旦您阅读了下一行,就无法返回行。

您需要做的是创建包含listemployee objectemployeeId的{​​{1}}对象(例如firstname)。填写列表并将其指定为lastname或类似内容的来源。

相关问题