8

我有一个有趣的问题。我正在尝试使用数据表作为数据网格视图的数据源。我想为表格的某些单元格着色以指示各种事物,但由于某种原因,颜色不会显示。所以下面的代码显示了一个未着色的单元格。

dataGridView1.DataSource = table;

dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;

我只能在初始表单加载后显示颜色(例如在 OnClick 事件上设置单元格颜色)。但是,如果我像下面的代码那样为视图显式创建行和列,则着色会起作用。

foreach (DataColumn col in table.Columns)
    dataGridView1.Columns.Add(col.ColumnName, col.ColumnName);

for (int i = 0; i < table.Rows.Count; i++)
{
    var row = table.Rows[i];
    object[] values = new object[table.Columns.Count];
    for (int x = 0; x < table.Columns.Count; x++)
        values[x] = row[x].ToString();

    dataGridView1.Rows.Add(values);
}

dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;

我不想以这种方式拥有代码。有谁知道这里发生了什么阻止我给细胞着色?

4

2 回答 2

22

如果您尝试在表单的构造函数中设置单元格颜色,您将在数据绑定完成之前点击,因此对单元格的更改不会粘住(不要问我为什么,只是其中一个带有DataGridView.

最直接的解决方法是稍后设置颜色 - 通常在DataBindingComplete事件处理程序中:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}

这适用于网格的静态着色 - 如果您希望颜色根据网格内的更改而更改,则使用CellFormatting事件来更改单元格。

于 2012-09-20T21:39:51.683 回答
6

这是我最近实现的东西,我不知道它是否有帮助??

private void dgvOutstandingReports_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                int colIndex = e.ColumnIndex;
                int rowIndex = e.RowIndex;


                if (rowIndex >= 0 && colIndex >= 0)
                {
                    DataGridViewRow theRow = dgvOutstandingReports.Rows[rowIndex];


                    if (theRow.Cells[colIndex].Value.ToString() == "Daily Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.LightYellow;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "Monthly Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.LightGray;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "SMP Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.Snow;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "Weekly Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.Pink;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "Hourly Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.LightSteelBlue;
                    }
                }
            }
于 2012-09-20T16:57:11.970 回答