You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中DataGridView根据员工职位角色设置行背景颜色的实现问题

Fixing DataGridView Row Coloring Issues in C#

Let's work through this problem step by step—first we'll fix that "invalid attempt" error, then implement the row coloring with if conditions as you requested.

First: Diagnose the "Invalid Attempt" Error

That error usually pops up for a few common reasons here:

  • You're trying to access the blank new row at the end of the DataGridView (it doesn't have valid cell values yet)
  • The column name "role" doesn't match the actual name in your DataGridView/DataTable
  • Your switch statement uses placeholder values ("a"/"b"/"c") instead of the real role names ("销售经理", "软件工程师", "项目经理") from your data

Step 1: Fix the Existing Code & Error

Here's an updated version of your code that handles edge cases and uses your actual role values:

private DataTable GetDataFromDB() { }

// Trigger coloring right after data loads
private void Form_Load(object sender, EventArgs e)
{
    // Bind your data first
    dataGridView1.DataSource = GetDataFromDB();
    // Color all rows once data is loaded
    ColorAllRows();
}

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // Skip invalid rows (new blank row or negative index)
    if (e.RowIndex < 0 || e.RowIndex == dataGridView1.NewRowIndex)
        return;
    
    if (dataGridView1.Columns[e.ColumnIndex].Name == "role")
    {
        ColorRow(dataGridView1.Rows[e.RowIndex]);
    }
}

private void ColorAllRows()
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        // Skip the blank new row at the end
        if (row.IsNewRow)
            continue;
            
        ColorRow(row);
    }
}

private void ColorRow(DataGridViewRow row)
{
    // Make sure the cell value exists and isn't null/DBNull
    if (row.Cells["role"].Value != null && !DBNull.Value.Equals(row.Cells["role"].Value))
    {
        string role = row.Cells["role"].Value.ToString().Trim();
        
        switch (role)
        {
            case "销售经理":
                row.DefaultCellStyle.BackColor = Color.Yellow;
                break;
            case "软件工程师":
                row.DefaultCellStyle.BackColor = Color.Red;
                break;
            case "项目经理":
                row.DefaultCellStyle.BackColor = Color.Blue;
                break;
            default:
                row.DefaultCellStyle.BackColor = Color.White;
                break;
        }
    }
    else
    {
        row.DefaultCellStyle.BackColor = Color.White;
    }
}

Step 2: Implement Row Coloring with If Conditions

If you prefer using if statements instead of switch, here's how to rewrite the ColorRow method:

private void ColorRow(DataGridViewRow row)
{
    if (row.Cells["role"].Value != null && !DBNull.Value.Equals(row.Cells["role"].Value))
    {
        string role = row.Cells["role"].Value.ToString().Trim();
        
        if (role == "销售经理")
        {
            row.DefaultCellStyle.BackColor = Color.Yellow;
        }
        else if (role == "软件工程师")
        {
            row.DefaultCellStyle.BackColor = Color.Red;
        }
        else if (role == "项目经理")
        {
            row.DefaultCellStyle.BackColor = Color.Blue;
        }
        else
        {
            row.DefaultCellStyle.BackColor = Color.White;
        }
    }
    else
    {
        row.DefaultCellStyle.BackColor = Color.White;
    }
}

Quick Reminders to Avoid Future Issues

  • Always check for row.IsNewRow before accessing cells—this is the #1 fix for that "invalid attempt" error
  • Double-check that your column's Name property is set to "role" (not just the HeaderText) since you mentioned read[2] is your role field
  • Run ColorAllRows() right after binding your data to the grid to color existing rows immediately

内容的提问来源于stack exchange,提问作者creative one2018

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:52:23