简体   繁体   English

C# DataGrid 单元格 - 更改行前景色 IF

[英]C# DataGrid Cell - Change row forecolor IF

I'm trying to change the forecolor of a specific row within a datagrid if a cell within that row contains the word "WARNING".如果该行中的单元格包含“警告”一词,我正在尝试更改数据网格中特定行的前景色。

 foreach (DataGridViewRow row in inclog.Rows)
        {
            if (inclog.SelectedCells[5].Value.ToString() == "WARNING")
            {

                inclog.SelectedRows[1].DefaultCellStyle.ForeColor = Color.Red;

            }
        }

I'm trying to change the code, add and remove bits but can't seem to be able to do it.我正在尝试更改代码,添加和删除位,但似乎无法做到。

There appears to be a complete disconnect from what the text in the question says and what the code is doing.似乎与问题中的文字内容和代码正在做什么完全脱节。 The posted code doesn't really make sense and I will assume that what the text in the question says is what you want.发布的代码并没有真正的意义,我会假设问题中的文字所说的就是你想要的。 Therefore, the solution below will do what is described in the text…因此,下面的解决方案将执行文本中描述的操作……

”I'm trying to change the forecolor of a specific row within a datagrid if a cell within that row contains the word "WARNING".” “如果该行中的单元格包含单词“WARNING”,我正在尝试更改数据网格中特定行的前景色。”

What I can decipher, is that for “each” row in the grid, if one of the cells in that row contains the word “Warning”, then, you want to set the fore color (text) in that row to red.我能理解的是,对于网格中的“每一”行,如果该行中的一个单元格包含“警告”一词,那么,您希望将该行中的前景色(文本)设置为红色。 If this is correct, then the code below should work.如果这是正确的,那么下面的代码应该可以工作。

In the code, we loop through each of the “Rows” in the grid (ignoring the “new” row if present), then another loop through each of the “Cells” in that row.在代码中,我们循环遍历网格中的每个“行”(如果存在则忽略“新”行),然后再循环遍历该行中的每个“单元格”。 A check is made to see if that cells text contains the word “Warning.”检查该单元格文本是否包含“警告”一词。 If the cell DOES contain the word “Warning”, then the code sets that row's fore color to red.如果单元格包含“警告”一词,则代码将该行的前景色设置为红色。 Then “breaks” out of the “Cells” loop as we do not need to check further for the text “Warning.”然后“中断”出“单元”循环,因为我们不需要进一步检查文本“警告”。

foreach (DataGridViewRow row in inclog.Rows) {
  if (!row.IsNewRow) {
    foreach (DataGridViewCell cell in row.Cells) {
      if (cell.Value != null && cell.Value.ToString().Contains("Warning")) {
        row.DefaultCellStyle.ForeColor = Color.Red;
        break;
      }
    }
  }
}

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

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