更改DataGridViewRow的BackColor

时间:2014-04-24 11:54:48

标签: c# winforms

我知道这个问题已经发生了很多。我可能已经检查了所有这些,但没有人为我工作。我有两个例子,我把它标记为我最喜欢的,并且认为应该可以工作,但它没有。

foreach (DataGridViewRow row in gridResults.Rows)
   row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#000000");

for (int row = 0; row < gridResults.RowCount; row++ )
    gridResults.Rows[row].DefaultCellStyle.BackColor = Color.Red;

出于某种原因,这些都不起作用。我已经尝试过stackoverflow用户建议的其他多个用户(以及那之外的intertube!) - 但它根本不起作用。

这让我想知道我是否在我的应用程序中获得了一些属性或类似的功能,从而使更改行背景颜色的能力失效。我知道这听起来很奇怪,但是有人认出这个问题吗?

2 个答案:

答案 0 :(得分:0)

看来,上面的代码只有在将它放入onLoad时才有效,我的是在构造函数中。这本身就是一个大错:P

答案 1 :(得分:0)

如果符合某些条件,Yoy可以处理两个可以处理单元格背景颜色的事件,是以下事件:

在绘制数据单元格之前引发 CustomDrawCell 事件。要绘制的单元格由RowCellCustomDrawEventArgs。RowHandle和RowCellCustomDrawEventArgs.Column参数标识。

请参阅以下示例:

private void advBandedGridView1_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e) 
{
   GridView currentView = sender as GridView;
   if(e.RowHandle == currentView.FocusedRowHandle) return;
   Rectangle r = e.Bounds;

   if(e.Column.FieldName == "UnitsInStock") 
   {
      bool check = (bool)currentView.GetRowCellValue(e.RowHandle, 
      currentView.Columns["Discontinued"]);

      if(check) 
      {
        //Change the text to display
        //The e.Handled parameter is false
        //So the cell will be painted using the default appearance settings
        e.DisplayText = "Discontinued";                    
       }
       else 
       {
        // If the cell value is greater then 50 the paint color is LightGreen, 
        // otherwise LightSkyBlue 
        Brush ellipseBrush = Brushes.LightSkyBlue;

        if (Convert.ToInt16(e.CellValue) > 50) ellipseBrush = Brushes.LightGreen;

        //Draw an ellipse within the cell
        e.Graphics.FillEllipse(ellipseBrush, r);
        r.Width -= 12;

        //Draw the cell value
        e.Appearance.DrawString(e.Cache, e.DisplayText, r);

        //Set e.Handled to true to prevent default painting
        e.Handled = true;
       }
   }
}

为单个单元格引发 RowCellStyle 事件,然后才需要重新绘制它们。可以使用事件的CustomRowCellEventArgs.RowHandleCustomRowCellEventArgs.Column参数来标识引用的单元格。 要自定义单元格的外观设置,请使用RowCellStyleEventArgs.Appearance属性。

请参阅以下示例:

private void gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e) 
{
    if(e.RowHandle != gridView1.FocusedRowHandle && ((e.RowHandle % 2 == 0 && e.Column.VisibleIndex % 2 == 1) || (e.Column.VisibleIndex % 2 == 0 && e.RowHandle % 2 == 1)))    
      e.Appearance.BackColor = Color.NavajoWhite;
 }

我希望这对你有所帮助。

相关问题