如何把数据添加到ListView中.....

vampire_dd 2007-02-23 07:58:52
SQL有表EmployyInfo
EmployyId EmployyName Dept ..省略
1 Tom 经理
2 Anna 副经理

我想在winform中通过SQL语句实现将表中的所有记录显示到ListView中
private void button6_Click(object sender, EventArgs e)
{
//查询所有员工
SqlConnection MyCon = SqlCon.CreateConnection();

SqlCommand command = new SqlCommand("select * from EmployyInfo", MyCon);
command.Connection.Open();
SqlDataReader newReader = command.ExecuteReader();
ListViewItem EmpIds=new ListViewItem();
ListViewItem.ListViewSubItem EmpNames=new ListViewItem.ListViewSubItem();
ListViewItem.ListViewSubItem Depts=new ListViewItem.ListViewSubItem();
while (newReader.Read())
{

EmpIds.Text = newReader.GetString(0);


EmpNames.Text = newReader.GetString(1);

Depts.Text = newReader.GetString(2);
EmpIds.SubItems.Add(EmpNames);
EmpIds.SubItems.Add(Depts);
listView1.Items.Add(EmpIds);


}
newReader.Close();
command.Connection.Close();

}
这样写好像只能显示第一行记录.当向表中有第二行记录时就会出错了..
小弟刚学C#,很多不明白.要怎么写才行呢.谢谢!
...全文
276 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
takekoputa 2007-02-25
  • 打赏
  • 举报
回复
不客气哈哈
vampire_dd 2007-02-23
  • 打赏
  • 举报
回复
谢谢
takekoputa 2007-02-23
  • 打赏
  • 举报
回复
while(dr.Read())
{
//if this is the first loop,we want to creat column headers
//in the listview
if(first)
{
listViewReault.Items.Clear();
listViewReault.Columns.Clear(); //所有列标头
for(int i=0;i<dr.FieldCount;i++) //FieldCount获取当前行中的列数
listViewReault.Columns.Add(dr.GetName(i).ToString(),100,HorizontalAlignment.Left);
//获取指定列的名称,长度,
//对齐方式
first=false;
}
//Add the row to the listview
for(int i=0;i<dr.FieldCount;i++)
{
if(i==0)
lvi=listViewReault.Items.Add(dr.GetValue(i).ToString());
else
lvi.SubItems.Add(dr.GetValue(i).ToString());

}
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧