我想根据绑定对象的属性为特定行添加背景色。

我的解决方案(并且有效)是使用 Event DataBindingComplete 但我认为这不是最好的解决方案。

这是事件:

    private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {

        for (int i = 0; i < this.myGrid.Rows.Count; i++)
        {
            if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
            {
                this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
            }
        }
    }

还有其他更好的选择吗?

有帮助吗?

解决方案

您还可以将事件处理程序附加到RowPostPaint:

dataGridView1.RowPostPaint += OnRowPostPaint;

void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;
    DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;

    // Do whatever you want with style and value
    ....
}

其他提示

我并没有真正使用WinForms,但在ASP中你会使用'ItemDataBound'方法。在Windows窗体中是否存在类似DataGrid的内容?

如果是这样,在该方法中,事件参数将包含数据绑定项以及DataGrid行。因此,通用代码看起来像这样(语法可能已关闭):

if(((MyObject)e.Item.DataItem).Special)
   e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);

我会建议几件事:

  • 查看在 _OnRowDatabound 处修改行
  • 不要在代码中设置颜色!这将是一个很大的错误。使用 attribute 属性并设置 cssclass。对仍在这样做的人摇动手指。

如果您在实施过程中遇到困难,请告诉我,我将发布一个片段。

private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{

    foreach (DataGridViewRow row in myGrid.Rows)
    {
        if((row.DataBoundItem as MyObject).Special)
        {
            row.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top