c#更改DataGridView Row BackColor

时间:2016-10-07 16:51:08

标签: c# datagridview

我有一个表来自数据库,当用户Cell[5]的值"Connected"更改该行的背景颜色时,它包含我想要的用户的一些信息:

这是我的功能:

        public void Initialize(DataGridView Dt)
        {

            foreach(DataGridViewRow Row in Dt.Rows)
            {
                if (Row.Cells[5].Value.ToString() == "Connected")
                {

                    Row.DefaultCellStyle.BackColor = Color.Green;
                }

                else
                {
                    Row.DefaultCellStyle.BackColor = Color.Red;

                }
            }

        }

一切都很完美,没有抛出异常,但我的行颜色在两种情况下都没有变化

请注意我使用MetroGridView

中的Metro Dll

1 个答案:

答案 0 :(得分:0)

您必须处理单元格格式化事件才能实现目标。 尝试下面的示例代码。它正在发挥作用。

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
              if(dataGridView1.Columns[e.ColumnIndex].Name == "C")
              {
                  if(e.Value != null)
                  {
                      String StringValue =(String)e.Value;
                      if (StringValue.IndexOf("C1") > -1)
                      {

                          dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                      }
                  }

              }

        }

Mu猜测,即使你正确行事,在稍后部分触发的单元格格式化事件也会覆盖你的更改。

相关问题