求教:VS 2005 WinForm 程序中DataGridView 和 DataBindingSource 的关联问题

chencang 2009-04-27 03:25:23
我用VS 2005 开发WinForm 程序,基本上都采用拖拽的开发模式
即从数据源中拖拽DataTable到界面中,VS就会在界面上自动产生DataGridView ,下方产生 BindingSource 和 TableAdapter

然后,我在DataGridView 中增加一个与数据源无关的CheckBox列,用来选择记录,并对选中记录操作,但是不成功,以删除功能为例,我写的删除代码如下:
foreach (DataGridViewRow row in this.tblMtrlDetailDataGridView.Rows)
{
DataGridViewCheckBoxCell checkBox = (DataGridViewCheckBoxCell)row.Cells["Selected"];

if ((bool)checkBox.FormattedValue)
{
this.tblMtrlDetailBindingSource.RemoveAt(row.Index);
}
}

当 tblMtrlDetailDataGridView 中记录全部打勾时,删除总是留有一条记录,再选中该记录点【删除】,才能删掉
我猜想问题可能出在 this.tblMtrlDetailBindingSource.RemoveAt(row.Index);
DataGridView 和 BindingSource 的索引对应关系
请大侠们帮忙!!!


另外,如果点击 DataGridView 的列头重新排序后,对 BindingSource 有没有影响?
...全文
106 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
chencang 2009-04-29
  • 打赏
  • 举报
回复
谢谢1楼,方法可行,正确代码:
for (int i = this.tblMtrlDetailDataGridView.Rows.Count - 1; i > -1; i--)
{
DataGridViewCheckBoxCell checkBox = (DataGridViewCheckBoxCell)this.tblMtrlDetailDataGridView.Rows[i].Cells["Selected"];

if ((bool)checkBox.FormattedValue)
{
this.tblMtrlDetailBindingSource.RemoveAt(i);
}
}

另外,点击 DataGridView 的列头重新排序后,BindingSource 中的数据也跟着排序,能按照选择的正确定位
冰凝瞬间1986 2009-04-28
  • 打赏
  • 举报
回复
建议用代码写,不要用向导
wuyq11 2009-04-27
  • 打赏
  • 举报
回复
修改后刷新显示
参考
himoggy 2009-04-27
  • 打赏
  • 举报
回复
不知道是不是RemoveAt的Index每次都重新计算了
反正listview里是这样的

你改成
for(int i=this.tblMtrlDetailDataGridView.Rows.Count-1;i>-1;i--)
{
DataGridViewCheckBoxCell checkBox = (DataGridViewCheckBoxCell)row[i].Cells["Selected"];


if ((bool)checkBox.FormattedValue)
{
this.tblMtrlDetailBindingSource.RemoveAt(i);
}
}

试试

不知道我有没有写错……

111,126

社区成员

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

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

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