但是当数据源是DataTable的时候, 改变DataGridView的Cell值,当改变一个值后,会重新触发DataGridView的DataBindingComplete事件,从而进行新的绑定操作,这样就陷入了一个死循环,程序无法执行下去,没有办法,后来改用了list,才解决了此问题

  最近用到DataGridView,在绑定完数据库,要根据一定的规则改变DataGridView的列值以及背景颜色,我首先用的是用的视图,从数据库获得一个表,然后赋值给DataGridView,在DataBindingComplete中,对行进行扫描,方法如下:

 

DataGridView的DataBindingComplete事件困惑_DataBindingCompleteDataGridView的DataBindingComplete事件困惑_DataGridView_02代码
private void dgvcardoor_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView curDgv = (DataGridView)sender;
foreach (DataGridViewRow Row in curDgv.Rows)
{
if (Row != null)
{
foreach (DataGridViewCell cell in Row.Cells)
{
if (curDgv.Columns[cell.ColumnIndex].DataPropertyName.Equals("IsModify"))
{
if (cell.Value.ToString().Equals("是"))
{
Row.DefaultCellStyle.ForeColor = Color.Blue;
Row.DefaultCellStyle.BackColor = Color.OrangeRed;
}
}
if (curDgv.Columns[cell.ColumnIndex].DataPropertyName.Equals("TopImgUrl"))
{
cell.Value = "俯视图像";
}
if (curDgv.Columns[cell.ColumnIndex].DataPropertyName.Equals("LeftImgUrl"))
{
cell.Value = "左视图像";
}
if (curDgv.Columns[cell.ColumnIndex].DataPropertyName.Equals("RightImgUrl"))
{
cell.Value = "右视图像";
}
}
}
}
}

 

 

  但是当数据源是DataTable的时候, 改变DataGridView的Cell值,当改变一个值后,会重新触发DataGridView的DataBindingComplete事件,从而进行新的绑定操作,这样就陷入了一个死循环,程序无法执行下去,没有办法,后来改用了list<>,才解决了此问题,在此记录一下,以免以后还会犯类似的错误;

  注意:

     1. 在WinFrm下的DataGridView控件

     2. 改变当前行CurrentRow,在DataGridView_CellClick事件中添加

       DataGridView.Rows[e.RowIndex].Selected = true;

     3. 在DataGridView里面获得的Cell值是更改后的值,你需要在后台重新的获得你想要的数据;

 

 

作者:不老神仙