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

DataGridView行颜色修改
本文介绍如何使用C#在DataGridView中通过DataBindingComplete事件更改特定行的颜色,并提供了具体的代码实现示例。

其实那一句改变行颜色的代码都会写,只是写在哪儿的问题。经研究,这句代码要写到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事件的详细信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值