首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改BackColor的DataGridViewRow

更改BackColor的DataGridViewRow
EN

Stack Overflow用户
提问于 2014-04-24 11:54:48
回答 2查看 143关注 0票数 0

我知道这个问题已经提了很多。我可能都查过了,但没人为我工作。我有两个例子,我标记为我的最爱,认为应该有效,但它没有。

代码语言:javascript
复制
foreach (DataGridViewRow row in gridResults.Rows)
   row.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#000000");

代码语言:javascript
复制
for (int row = 0; row < gridResults.RowCount; row++ )
    gridResults.Rows[row].DefaultCellStyle.BackColor = Color.Red;

因为某种原因,这些不起作用。我已经尝试过来自堆栈溢出用户的多个建议(以及外部的插槽!)--但是它根本不起作用。

这让我想知道,我的应用程序中是否有一些属性或相似的属性,使我无法激活更改行背景色的能力。我知道这听起来很奇怪,但有人认识这个问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-24 12:13:58

看起来,上面的代码只在把它放在onLoad中时才能工作,我的代码在构造函数中。这本身就是一个很大的错误

票数 0
EN

Stack Overflow用户

发布于 2014-04-24 12:22:47

Yoy可以处理两个事件,如果满足某些条件,可以处理单元格的背景色,这些事件如下:

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

请参见以下示例:

代码语言:javascript
复制
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属性。

请参见以下示例:

代码语言:javascript
复制
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;
 }

希望这能帮到你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23268167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档