如何用不同的颜色初始化数据网格中的一些行

本文关键字:网格 数据网 数据 何用不 颜色 初始化 | 更新日期: 2023-09-27 18:25:05

我想根据特定条件将DataGridView的一些行初始化为红色。问题是,我一直在玩,但当DataGridView显示时,我无法让它发挥作用。我试着在MainForm的构造函数中这样做,但一点运气都没有。

private void UpdateSoldOutProducts ()
    {
        for (int i = 0; i < productsTable.Rows.Count; i++)
            if ((int)productsTable.Rows [i] ["Quantity"] == 0)
                dataGridViewProducts.Rows [i].DefaultCellStyle.BackColor = Color.Red;
    }

此方法在MainForm的构造函数中被调用。

如何用不同的颜色初始化数据网格中的一些行

尝试RowPostPaint事件,它对我有效:

private void dataGridViewProducts_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if ((int)dataGridViewProducts.Rows[e.RowIndex].Cells["Quantity"].Value == 0)
                    dataGridViewProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
        }

您可以使用自定义绘制绘制DataGridView行和单元格。它是用DataGridView.RowPostPaint事件和DataGridView_RowPrePaint事件。

另一个期望是Paint Event

private void dataGridViewProducts_Paint(object sender, PaintEventArgs e)
        {
            foreach (DataGridViewRow row in dataGridViewProducts.Rows)
            {
                int value = Convert.ToInt32(row.Cells["Quantity"].Value);
                if (value == 0)
                    row.DefaultCellStyle.BackColor = Color.Red;
            }
        }

您可以使用DataGridViewRowPostPaintEventArgsData_GridViewRowPrePaintEventargs

您可以单独处理此事件,也可以与RowPrePaint事件组合处理,以自定义控件中rows的外观。您可以自己paint整行,也可以绘制行的特定部分,并使用DataGridViewRowPostPaintEventArgs类的以下方法绘制其他部分:

  • DrawFocus

  • PaintCells

  • PaintCellsBackground

  • PaintCellsContent

  • PaintHeader

请查看MSDN链接上的此示例,并尝试为其中一个事件编写代码。。在这里,您将使用DataGridViewRowPostPaintEventArgs获得Current行索引

int value = Convert.ToInt32(dataGridViewProducts.Rows[e.RowIndex].Cells["Quantity"].Value);
if (value == 0)                     
dataGridViewProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;  

编辑:将代码放在Form Load事件或DataBinding Completed事件上。愿这能解决你的问题。