2015-11-17 96 views
-1

我无法找到问题出在哪里,当我把while循环,因为它工作的意见,之后while循环,我们不能从SqlDataReader的更多阅读? listbox2仍然是空的!为什么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

添加来自阅读器的项目列表,而不是设置数据源给读者。我认为这个问题是'reader'是一个迭代器,并且你已经遍历一次了,所以你的时间设置源给读者,它没有留下任何物品。 –

+0

'ListBox2.DisplayMember = “姓名”; ListBox2.ValueMember =“姓氏”;'试试..还怎么可能雇员永远是一个使用时,它不是你原来的选择查询 'ListBox2.DataSource =读者的一部分;'应设置最后 – MethodMan

+0

emloyeeid是查询的一部分在字符串sql中,Iam仍然困惑 –

回答

0

不能再次使用reader。 从MSDN Doc

提供从SQL Server数据库中读取一个只进行流的方式。

您可以一次读取一行,但是一旦读完下一行就不能返回到一行。

你必须做的是,你必须创建一个包含employeeIdfirstnamelastname对象(例如employee object)的list。填充列表并将其指定为list2或类似的东西的来源。

相关问题