2012-02-18 78 views
2

我想根据一定的条件初始化我的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的的构造卡勒。

回答

0

你可以画用油画定制DataGridView的行和单元格。它用 ,DataGridView.RowPostPaint EventDataGridView.RowPrePaint Event完成。

另一个期望是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; 
      } 
     } 

您可以使用DataGridViewRowPostPaintEventArgsDataGridViewRowPrePaintEventArgs设置的条件的基础上,行或单元格样式..

可以单独使用或与RowPrePaint事件组合处理此事件定制在控件中出现rows。您可以paint整个行自己,或油漆行的特定部分,并使用DataGridViewRowPostPaintEventArgs类的以下方法来绘制其他部分:

  • DRAWFOCUS

  • PaintCells

  • PaintCellsBackground

  • PaintCellsContent

  • PaintHeader

检查MSDN链接这个例子,并尝试把你的代码,这些事件之一..在这里,你,你会使用DataGridViewRowPostPaintEventArgs

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

得到Currrent行索引编辑: 把你的代码放在表单加载事件或DataBinding完成的事件。这可以解决你的问题。

+0

试着把我的代码放在** Form_Load **方法中,但没有任何反应。我会尝试** Paint **或** PrePaint **事件。我不明白的是,** DataGridView **的** Paint **或** PrePaint **事件将使用** DefaultCellStyle.BackColor **绘制单元格的颜色。所以,如果我改变属性的值** BackColor **为什么我必须自己处理** Paint **事件? – user990692 2012-02-18 14:53:27

+0

兄弟你是否试过** Row ** PostPaint,因为它的功能完美 – 2012-02-18 15:01:22

+0

没有我的朋友,但我会尝试。我没有尝试过。感谢您的帮助:)) – user990692 2012-02-18 16:20:37

2

尝试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; 
     } 
相关问题