简体   繁体   English

C#更改DataGridView行的BackColor

[英]c# Change DataGridView Row BackColor

I have a Table From Database That holds Some informations about users i want when the Value of The User Cell[5] is "Connected" to change the backcolor of that row : 我有一个来自数据库的表,其中包含“用户Cell[5] "Connected"的值"Connected"以更改该行的背景色时我想要的用户的一些信息:

here is my function : 这是我的功能:

        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;

                }
            }

        }

Everything work perfect no exceptions where thrown but My row color didnt change in both cases 一切正常,没有异常,但是在两种情况下我的行颜色都没有改变

Please Note That im using MetroGridView from Metro Dll 请注意,即时通讯使用的是Metro Dll MetroGridView

You have to handle cell formatting event to achieve your goal. 您必须处理单元格格式化事件才能实现目标。 Tried a sample code below. 尝试了下面的示例代码。 It is working. 这是工作。

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 guess is, even though you are doing it right, the cell formatting event which triggers at later part, is overriding your changes. Mu猜测是,即使您做得正确,但稍后触发的单元格格式化事件将覆盖您的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM