我用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 有没有影响?

解决方案 »

  1.   

    不知道是不是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); 
                    } 
    }试试不知道我有没有写错……
      

  2.   

    谢谢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 中的数据也跟着排序,能按照选择的正确定位