【问题标题】:How to change datagridview row color based on string value如何根据字符串值更改datagridview行颜色
【发布时间】:2015-10-09 04:04:09
【问题描述】:

我尝试在论坛中搜索以找到答案,但它们似乎都在检查整数值,而不是字符串。 我有一个 C# 表单从 SQL 表中提取数据值并将它们显示在 datagridview 上。我希望检查字符串值的列标记为“类型”,并且是我数据表中的第三列。我希望在第三列中突出显示所有包含“pharmacy”一词的红色行。

private void invTableDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow row in invTableDataGridView.Rows)
        {
            if (row.Cells[2].Value.ToString() == "Pharmacy")
            {
                invTableDataGridView.DefaultCellStyle.BackColor = Color.Red;
            }
        }

    }

当我使用这段代码运行程序时,没有任何变化,即使我执行了应该触发 databindingcomplete 事件的操作。令人沮丧的是,如果我将 row.Cells[2] 更改为 row.Cells[3] 我有整数值,然后键入

    if (row.Cells[3].Value.ToString() == "0")

代码有效,但用于错误的列。它似乎只适用于整数,但我希望它适用于字符串。我该怎么做?

编辑:是的,对不起,我应该一直保持一致。我希望比较的值是“Pharmacy”,大写。

Edit2:好的,我知道为什么它给我带来了这么多麻烦。 column[2] 中的值是由组合框添加的,由于某种原因,它总是在单词后添加两个空格,即使它没有在字符串集合编辑器中显示空格。

【问题讨论】:

  • == 必须是 .Equals("Pharmacy")
  • @Cageman 我尝试将 if (row.Cells[2].Value.ToString() == "Pharmacy") 替换为 if (row.Cells[2].Value.ToString().Equals (“药房”))但它没有用。这是否意味着其他地方也有问题?
  • 在字符串上它也可以工作。在您写的问题中,值必须是“药房”,但在您与“药房”进行比较的代码中。如果数据包含小写版本,则比较将返回 false。
  • @Fabio 这就是我的意思,现在还早,我应该更好地解释一下 +1 给你 :-)
  • @anesthetic 在为数据网格着色后进行刷新:base.refresh()

标签: c# string datagridview colors rows


【解决方案1】:

因为您的代码适用于整数列,所以问题必须在字符串比较中。
正如我在 cmets 中提到的,检查您拥有的数据以及与之相比的价值。
或者您可以对单元格值执行ToLower() 并将其与“药房”进行比较
您可以使用CellFormatting 事件处理程序。这个事件应该有利于基于值的格式化控制

private void invTableDataGridView_CellFormatting(Object sender,
                                                 DataGridViewCellFormattingEventArgs e)
{
    Int32 yourindexColumn = 2;
    if (e.RowIndex < 0 || e.ColumnIndex <> yourindexColumn)
        Return;
    //Compare value and change color
    DataGridViewCell cell = invTableDataGridView.Rows[e.RowIndex].Cells[yourindexColumn]
    String value = cell.Value == null ? string.Empty : cell.Value.ToString()
    if (value.ToLower().Equals("pharmacy") == true)
    {
        invTableDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    }
}

【讨论】:

  • 这个成功了!谢谢!我尝试添加 +1,但它说我没有足够的代表来公开显示它。
猜你喜欢
  • 2018-05-12
  • 1970-01-01
  • 2023-04-06
  • 2022-06-11
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 2020-06-14
相关资源
最近更新 更多