【问题标题】:How to set the background color for specified row in datagridview?如何在datagridview中设置指定行的背景颜色?
【发布时间】:2015-02-15 23:18:21
【问题描述】:

我想为 datagridview 中的指定行设置背景颜色.. 我的需要是我有一个 for 循环 (i=0;i<10;i++) 。在这个 for 循环中我编写逻辑 作为

if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[1].DefaultCellStyle.SelectionBackColor = Color.Yellow;
}

if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[2].DefaultCellStyle.SelectionBackColor = Color.Blue;
}


if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[3].DefaultCellStyle.SelectionBackColor = Color.Red;
}

但我没有得到预期的 o/p 。我希望你理解我的需要。请帮帮我。

【问题讨论】:

标签: c# datagridview


【解决方案1】:

您可以按如下方式使用 DataGridview 的 SelectedRows 属性,而不是使用该属性

dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red;

因为SelectedRows 属性将在仅由用户选择行时返回行,如果没有选择行,那么您的代码将抛出异常。

编辑:

对于您的疑问,这里提供一个示例代码,希望它对您有所帮助。

for (int i = 0; i < 10; i++)
 {
   if (dataGridView1.Rows.Count > i)
    {
      if (i == 1)
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
      else if (i == 2)
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue;
      else
         dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green;
     }
 }

【讨论】:

    【解决方案2】:

    您可以处理数据网格的不同事件并设置单元格样式

    这是来自related question的示例

    private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex != color.Index)
            return;
    
        e.CellStyle.BackColor = Color.Red;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-29
      • 2014-08-06
      • 2011-03-11
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2017-12-02
      • 2010-12-11
      • 2020-12-14
      相关资源
      最近更新 更多