【问题标题】:WinForm DataGrid Change cell colorWinForm DataGrid 更改单元格颜色
【发布时间】:2021-04-06 17:55:53
【问题描述】:

我在 WinForm 项目中有一个 DataGrid 对象

Friend WithEvents StatusTable As System.Windows.Forms.DataGrid

我还有一个 DataSet Private StatusDS As Data.DataSet,其中包含加载到 StatusTable 中的数据,例如

StatusTable.DataSource = StatusDS.Tables("Channels")

一切正常,但现在我必须在第 3 列和第 x 行为“12”时更改整行背景颜色

我的第 3 列是一个字符串,名为 Act

我的专栏更新喜欢

 Dim ts As New DataGridTableStyle

 Dim Act As New DataGridTextBoxColumn

 Act.MappingName = "Act"
 Act.Alignment = HorizontalAlignment.Center
 Act.HeaderText = "Action"
 
 ts.GridColumnStyles.Add(Act)

 StatusTable.TableStyles.Add(ts)

如果列 act 和行 X 为“12”,我找不到任何方法来更改行背景颜色

例如,如果我有这张桌子

Act
"1"
"12"
"1"
"4"
"12"

我必须更改第 2 行和第 5 行的颜色(从 1 开始)

我有很多代码,我尽量放在这里。如果您遗漏任何信息,请告诉我

【问题讨论】:

  • 从 .NET Core 3.1 开始,DataGrid 控件不再可用:link。如果您希望您的项目能够长久使用,请改用DataGridView

标签: c# .net winforms datagrid


【解决方案1】:

注意:问题是关于 Windows Forms .NET DataGrid 在 .NET CORE 和 .NET 5 中已弃用且不再可用。 强烈建议升级您的解决方案以使用DataGridView

无论如何,如果您被 DataGrid 卡住并且无法轻松更新到 DataGridView,那么答案就是给您。

自定义 DataGrid 的外观

要自定义一个DataGrid控件,通常需要定义一个DataGridTableStyle,并在其中添加几个DataGridColumnStyle

要完全控制行和列的外观,您通常需要从现有的内置列样式之一(如DataGridTextBoxColumnDataGridBoolColumn 或基本DataGridColumnStyle)驱动来创建自定义列样式。然后,您可以通过覆盖类的属性和方法来自定义行为。

你会发现这篇文章非常有用:

示例 - 根据特定列的单元格值更改行背景颜色

在这里,我通过从内置的DataGridTextBoxColumn 派生并覆盖其Paint 方法来创建新的列样式。在方法中,我检查第一列的值是否为奇数:

public class MyDataGridTextBoxColumn : DataGridTextBoxColumn
{
    protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source,
        int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
    {
        var idCellValue = ((DataRowView)source.List[rowNum])["Id"];
        var brush = backBrush;
        if (idCellValue != DBNull.Value && ((int)idCellValue) % 2 == 1)
            brush = Brushes.Yellow;
        base.Paint(g, bounds, source, rowNum, brush, foreBrush, alignToRight);
    }
}

然后使用它:

private void Form1_Load(object sender, EventArgs e)
{
    var dt = new DataTable();
    dt.Columns.Add("Id", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Rows.Add(1, "A");
    dt.Rows.Add(2, "B");
    dt.Rows.Add(3, "C");

    var dg = new DataGrid();
    dg.Dock = DockStyle.Fill;
    var ts = new DataGridTableStyle();
    ts.GridColumnStyles.Add(new MyDataGridTextBoxColumn()
    { MappingName = "Id", HeaderText = "Id" });
    ts.GridColumnStyles.Add(new MyDataGridTextBoxColumn()
    { MappingName = "Name", HeaderText = "Name" });
    dg.TableStyles.Add(ts);

    this.Controls.Add(dg);
    dg.DataSource = dt;
}

你会看到结果:

注意: 不将任何业务逻辑放在自定义 Column 中肯定更有意义,相反您可以引发 Formatting 事件,并将任何逻辑放在事件处理程序中并将格式化数据传回给列,使用事件参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-29
    • 2023-03-28
    • 1970-01-01
    • 2015-12-16
    • 2018-09-26
    • 2011-09-12
    相关资源
    最近更新 更多