根据可编辑属性设置DataGridView列的背景颜色

3
我是一个有用的助手,可以翻译文本。

我通过直接分配数据表,从数据库填充DataGridview。在DataGridview中有一些可编辑的列和一些不可编辑的列。我想将可编辑列的颜色设置为“黄色”。

我知道可以像下面这样设置列的颜色:

myGrid.Columns["myColumn"].DefaultCellStyle.BackColor = Color.Red;

但如何检查可编辑属性并基于此设置颜色?

更新: 这就是我要找的……黄色单元格应该是可编辑的。基本上,在“批发率”、“零售率”等下面的单元格应该是可编辑的。

输入图像描述

3个回答

1

据我理解您的问题,您想要更改可编辑的datagridview中的单元格颜色?

您可以通过使用datagridviewDataGridViewCellFormattingEvent事件,并检查列是否为readonly,然后更改datagridviewcell的背景来实现此目的。

private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (!dgv.Columns[e.ColumnIndex].ReadOnly)
    {
        e.CellStyle.BackColor = Color.Yellow;
    }
}

输出:

enter image description here


我在 if语句 中的 dgv 前面添加了 ! - Shift 'n Tab
在DataGridView列设置中,您是否将一些不可编辑的列设置为“只读”?这样应该可以正常工作。 - Shift 'n Tab
我认为这是绑定网格的完整代码http://paste.ofcode.org/XmmGJHMi2AeS2zcx7S7zcF .. 您能检查一下吗? - techno
如果手动进入设计器,在右上角的小箭头中会出现一个菜单,选中“启用编辑”,然后进入“编辑列”并将所有不可编辑的列设置为readonly属性。 - Shift 'n Tab
我已经将 ReadOnly=false 设置为3列。只有1个单元格显示为黄色。其他2个单元格只有在我点击它们后才会变成黄色。 - techno
显示剩余6条评论

0

使用RowPostPaint事件

void dataGridView1_RowPostPaint(object sender,
    DataGridViewRowPostPaintEventArgs e)
{
    foreach ( DataGridViewRow row in dataGridView1.Rows )
    {
        if ( row.Cells["myColumn"].Value == "editable" )
            row.Cells["myColumn"].Style.BackColor = Color.Yellow;
        else
            row.Cells["myColumn"].Style.BackColor = Color.Red;
    }
}

你也可以重写 paint 方法,如 这里 所述。


谢谢..但是我一直收到这个错误object' does not contain a definition for 'Cells' and no extension method 'Cells' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?),针对rows.Cells。 - techno
现在尝试一下。我更新了我的回答。 - Blue
谢谢...但我不能像这样通过列名进行迭代row.Cells["myColumn"].Value..有没有一种方法可以在for each循环中迭代它。 - techno
如果你只需要一列,那么可以直接使用 row.Cells[1] 访问它。 - Blue
这并不检查列是否可编辑,而是检查单元格的 value 是否包含文本“editable”。 - Shift 'n Tab
显示剩余2条评论

0

这只是一个示例代码,使一列可编辑,dgvSample是您在表单中添加的DataGridView。在这里,我已经使所有奇数列可编辑。因此,以同样的方式,您可以拥有带复选框的隐藏列,并检查其是否可编辑并实现相同的效果。

dgvSample.AllowUserToAddRows = false;
dgvSample.AllowUserToDeleteRows = false;

for (int i = 0; i <= 10; i++)
{
    string[] values = new string[] { "1", "Name" };
    dgvSample.Rows.Add(values);
    if (i % 2 == 0)
    {
        DataGridViewRow r = dgvSample.Rows[dgvSample.Rows.Count - 1];
        r.ReadOnly = true;
    }
    else
    {
        r.DefaultCellStyle.BackColor = Color.Yellow;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接