使用数据源时不能更改datagridview的单元格颜色 [英] Can't change datagridview cell color when using a datasource

查看:1359
本文介绍了使用数据源时不能更改datagridview的单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的问题。我试图用一个数据表作为一个DataGridView的数据源。我想要的颜色的一些表以指示各种事物的细胞,但由于某些原因的颜色将不显示。所以下面的代码显示未着色单元

I've got an interesting issue. I am trying to use a datatable as a data source for a datagridview. I want to color some of the cells of the table to indicate various things, but for some reason the color will not display. So the following code shows an uncolored cell.

dataGridView1.DataSource = table;

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



我只能得到一个彩色的最初形式加载后显示(例如在设置单元格颜色OnClick事件)。不过,如果我明确地创建视图的行和列,如下面的代码中,着色的作品。

I can only get a color to display after the initial form load (for example setting a cell color on the OnClick event). However, if I explicitly create the rows and columns for the view as in the code below, the coloring works.

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;



我不希望有这种方式的代码。有谁知道发生了什么这里是阻止我着色细胞?

I do not want to have the code in this manner. Does anyone know what is happening here that is preventing me from coloring the cells?

推荐答案

如果你尝试中设置单元格颜色你将数据绑定完成这样的变化对细胞不沾之前击中窗体的构造函数(不要问我为什么,只是用 DataGridView中的陷阱之一

If you try and set the cell colour within the constructor of the form you will be hitting before the data binding is completed so the changes to the cells don't stick (don't ask me why, just one of those gotchas with the DataGridView.

最直接的修复程序,这是一个有点晚来设置颜色 - 通常在一个 DataBindingComplete 事件处理程序:

The most straightforward fix to this is to set the colours a little later - usually within a DataBindingComplete event handler:

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

这是适用于电网的静态色彩 - 如果你想要的颜色根据网格内的变化,然后使用 CellFormatting 事件来改变细胞的改变

This is appropriate for static colouring of the grid - if you want the colours to change according to the changes within the grid then use the CellFormatting event to change the cells.

这篇关于使用数据源时不能更改datagridview的单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆