2013-01-14 47 views
1

我试图从ID的表单加载事件中将存储过程的员工数据加载到listbox中,并为它们分配一个图像。上面的代码是我迄今为止所做的。所以我想在这里做的是填充listview来自我的数据阅读器的数据。列表框和SqlDataReader问题

SqlConnection conn = new SqlConnection(
          @"Data Source=MyPC\Test;Initial Catalog=TEST5;Integrated Security=True"); 
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn); 
cmd.CommandType = CommandType.Text; 

SqlDataReader dr = cmd.ExecuteReader(); 

listView1.Items.Clear(); 

while (dr.Read()) 
{ 
    ListViewItem recs = new ListViewItem(); 

    recs.Text = dr["dept_name"].ToString(); 
    recs.Text = dr["emp_first_name"].ToString(); 
    recs.Text = dr["emp_last_name"].ToString(); 
    recs.Text = dr["emp_email"].ToString(); 
    recs.Text = dr["emp_phone"].ToString(); 
    recs.Text = dr["emp_position"].ToString(); 
    recs.Text = dr["emp_address1"].ToString(); 
    recs.Text = dr["emp_address2"].ToString(); 
    recs.Text = dr["emp_city"].ToString(); 
    recs.Text = dr["emp_state"].ToString(); 
    recs.Text = dr["emp_postal_code"].ToString(); 

    recs.Tag = dr["empId"].ToString(); 
    recs.ImageIndex = 0; 
    listView1.Items.Add(recs); 
} 

在此先感谢您。

回答

2

您的查询目前只返回一个fieid:

SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn); 

我猜你想这样的:

SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn); 

您需要打开连接并关闭您的可支配资源。您当前的代码不断更换recs.Text属性,以至于您应该在列表中看到的唯一内容是“emp_postal_code”值。我怀疑您正在寻找这样的事情,在这里显示的用户名作为ListViewItem的主要项目再包括其他信息作为项目的子项(在详细视图中显示时):

listView1.Items.Clear(); 

using (SqlConnection conn = new SqlConnection(...)) { 
    conn.Open(); 
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn)) { 
    using (SqlDataReader dr = cmd.ExecuteReader()) { 
     while (dr.Read()) { 
     ListViewItem recs = new ListViewItem(); 

     recs.Text = dr["emp_first_name"].ToString() + " " + 
        dr["emp_last_name"].ToString(); 

     recs.SubItems.Add(dr["dept_name"].ToString()); 
     recs.SubItems.Add(dr["emp_email"].ToString()); 
     etc... 

     recs.Tag = dr["empId"].ToString(); 
     recs.ImageIndex = 0; 
     listView1.Items.Add(recs); 
     } 
    } 
    } 
} 
+0

我试过了。是否有一个属性设置为所有的listview来显示它的负载内容? –

+0

@JodieThatOneGuyLogan正如Joel在他的回答中提到的那样,连接并没有打开。您从未记录过问题所在 - 是否有错误?你看到你没有想到的结果是什么? – LarsTech

+0

对不起,迟到的回应...我试图做的是将我的员工表中的数据加载到数据读取器中,将结果显示在每个记录的可点击图像的列表视图中,以便单击记录时,详细信息将显示在单独的表格中。 –

0

我在这里看到几件事情:

  1. 你永远不打开连接:
  2. 你引用一个数字,不包含在你的语句的SELECT子句中的阅读器领域。
  3. 您覆盖而不是附加到ListViewItem的文本属性,以便只显示最后分配的属性值。