纸上得来终觉浅,绝知此事要躬行。

 

WinForm里面改变DataGridView某一行的背景颜色

其实那一句改变行颜色的代码都会写,只是写在哪儿的问题。经研究,这句代码要写到DataGridView里面的某个事件里面。例如:

privatevoid dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
  
int index = CardCMD.PublicInfoCom.GetLendRecordIndex();
  
if (index ==0)
  {
    
this.dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
    
this.dataGridView1.Rows[0].Selected =false;
    
this.dataGridView1.Rows[1].DefaultCellStyle.BackColor = Color.Wheat;
    
this.dataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Wheat;
  }
  
else if (index ==1)
  {
    
this.dataGridView1.Rows[1].DefaultCellStyle.BackColor = Color.Red;
    
this.dataGridView1.Rows[0].Selected =false;
    
this.dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Wheat;
    
this.dataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Wheat;
  }
  
else if (index ==2)
  {
    
this.dataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Red;
    
this.dataGridView1.Rows[0].Selected =false;
    
this.dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Wheat;
    
this.dataGridView1.Rows[1].DefaultCellStyle.BackColor = Color.Wheat;
  }
}

这段代码本人试验过,就是想要的效果,可以改变某一行或者某些行,改变某些行可以如下所写:

privatevoid rowMergeView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
  
//updateview();
  for (int i =0; i <this.rowMergeView1.Rows.Count; i++)
  {
    
try
    {
      
this.rowMergeView1.Rows[i].DefaultCellStyle.BackColor = Color.FromName(softcolor[this.rowMergeView1.Rows[i].Cells["yujing"].Value.ToString()]);
    }
    
catch (Exception ex)
    {
      
new FileOper().writelog(ex.Message);
    }
  }
}
 

如果要添加列或者行的话,也要在这个事件里面。但是列或者行的值每改变一次就会触发一次这个事件。可以去网上查一下DataBindingComplete事件的详细信息。

posted on 2010-11-24 16:27  JRoger  阅读(27975)  评论(2编辑  收藏  举报

导航