日期:2014-05-17  浏览次数:20824 次

分都给了!急求dataGridView动态添加数据的问题!
窗口界面中有两个dataGridView。dataGridView1已经绑定了一个表的几个字段,要求从dataGridView1中勾选的行数取出这个表的序号字段,然后根据序号字段从数据库中读取其他几个字段数据添加到dataGridView2中,修改后在保存到数据库另一个表中,我现在已经从dataGridView1中取得了序号存到一个数组中list[n]。然后在做了一个循环
for(int i=0;i<n;i++)
{
  sql = "...where ID = '"+ list[i].tostring+"'";
  dataGridView2.DataSource = ds.table[0];
  dataGridView2.Rows[i].Cells[1].Value = ds.Tables[0].Rows[0]["字段1"].ToString(); //根据序号取值Table里面只可能有一条数据
  dataGridView2.Rows[i].Cells[2].Value = ds.Tables[0].Rows[0]["字段1"].ToString(); 
  ...
}

这么每次运行,只选取一个序列号还可以实现,选取两条以上序号就报错:索引超出范围,不晓得思路哪出错了,请大家看看

------解决方案--------------------
探讨
这是我的源码,我测试了的,只能插入一条数据,第二条就把第一条覆盖了,在网上查的说是先把数据导入到Table,在绑定到datagridview中,不知道怎么操作

------解决方案--------------------
for(int i=0;i<n;i++)
{
sql = "...where ID = '"+ list[i].tostring+"'";
dataGridView2.DataSource = ds.table[0];
dataGridView2.Rows[i].Cells[1].Value = ds.Tables[0].Rows[0]["字段1"].ToString(); //根据序号取值Table里面只可能有一条数据
dataGridView2.Rows[i].Cells[2].Value = ds.Tables[0].Rows[0]["字段1"].ToString(); 
...
}

每次直查了一条数据,就更新了dataGridView2的数据源,因此,你的dataGridView2的数据只有你list中的最后一条数据,你把sql语句重新拼一下
sql = "...where ;
for(int i=0;i<n -1;i++))
{
sql += "ID = " + =list[i].ToString() + " || ";
}
sql += "ID = " + =list[list.Count - 1].ToString() ;

这样能把数据全部查出来,然后你只要绑定一次DataSource就行了。