为什么列表框2仍然为空
本文关键字:列表 为什么 | 更新日期: 2023-09-27 18:22:14
我找不到问题出在哪里,当我把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();
}
}
您不能再次使用reader
。来自MSDN Doc
提供了一种从SQL Server数据库中读取仅向前行流的方法。
您可以一次读取一行,但一旦读取了下一行,就不能返回到另一行。
您要做的是创建一个对象(例如employee object
)的list
,该对象包含employeeId
、firstname
和lastname
。填写列表并将其指定为list2
或类似内容的源。