DataGridView的DataBindingComplete事件困惑

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

 

代码
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值是更改后的值,你需要在后台重新的获得你想要的数据;

 

 

posted @ 2010-07-19 13:39  岩仔  阅读(5469)  评论(0编辑  收藏  举报