【问题标题】:Set the Backcolor of DataGridview Column Based on Editable Property基于 Editable 属性设置 DataGridview 列的背景色
【发布时间】:2016-12-02 07:52:48
【问题描述】:

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

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

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

但是如何检查可编辑属性并根据它设置颜色呢?

更新: 这就是我要找的...黄色单元格应该是可编辑的..基本上说 WholeSaleRate,Retail Rate.. 等下面的单元格应该是可编辑的。

【问题讨论】:

    标签: c# .net datagridview


    【解决方案1】:

    我能理解您的问题,您想更改datagridview 的可编辑cells 的颜色?

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

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

    输出:

    【讨论】:

    • 我试过了..但黄色显示为不可编辑的单元格并且是随机的..
    • 我在if statement 中的dgv 之前添加了!
    • 这是我使用的private void dgvGetData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (!dgvGetData.Columns[e.ColumnIndex].ReadOnly) { e.CellStyle.BackColor = Color.Yellow; } }
    • 使用这个if语句if(!dgv.Columns[e.ColumnIndex].ReadOnly)
    • 在 datagridview 列设置中,您是否将一些不可编辑的列设置为readonly?它应该可以正常工作。
    【解决方案2】:

    使用RowPostPaint event

    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 方法,如here 所述。

    【讨论】:

    • 谢谢 .. 但是对于 rows.Cells 不断收到此错误 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?)
    • 等一下,看看。
    • 立即尝试。更新了我的答案
    • 谢谢......但我不能通过给出这样的列名来迭代 row.Cells["myColumn"].Value .. 有没有办法在 for each 循环中进行迭代。跨度>
    • 如果您只是在寻找一列,请直接使用row.Cells[1]访问它
    【解决方案3】:

    这只是使列可编辑的示例代码,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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 2018-06-15
      • 1970-01-01
      相关资源
      最近更新 更多