我正在尝试通过listbox
将表单加载事件中的员工数据从存储过程加载到ID
,并为每个数据分配一个图像。上面的代码是我到目前为止的代码。所以我在这里要做的就是用我的数据阅读器中的数据填充listview
。
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);
}
提前谢谢。
答案 0 :(得分: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的主要项目,然后包含其他信息作为项目的SubItems(用于在详细视图中显示时):
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);
}
}
}
}
答案 1 :(得分:0)
我在这里看到了几件事: