如何根据字符串值更改datagridview行颜色

How to change datagridview row color based on string value

我尝试在论坛中搜索以找到答案,但它们似乎都在检查整数值,而不是字符串。 我有一个 C# 表单从 SQL table 中提取数据值并将它们显示在数据网格视图上。我希望检查字符串值的列标记为 "Type",并且是我的数据中的第三列 table。我希望在第三列中以红色突出显示包含单词 "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] 中的值是由组合框添加的,由于某种原因它总是在单词后添加两个空格,即使它没有在字符串集合编辑器中显示空格。

因为您的代码使用整数列,所以问题一定出在字符串比较中。
正如我在评论中提到的,检查你拥有的数据和与之相比的价值。
或者您可以对单元格值执行 ToLower() 并将其与 "pharmacy"
进行比较 您可以使用 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;
    }
}