2012-01-12 35 views
1

我需要根据数据值更改gridview单元格的颜色。我可以很容易地使用GridView RowDataBound Event和if语句中的数据行视图来完成此操作(请参阅下文),但是我需要在30列上执行此操作,这将会非常冗长,并且如果业务规则更改,则需要更改。我如何将以下内容封装到可以调用的可重用方法中,并只传递数据列和单元格索引?可重用的方法来更改gridview单元格颜色

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.DataItem != null) 
     { 
      DataRowView drv = (DataRowView)e.Row.DataItem; 

      int A = Int32.Parse(drv["A"].ToString()); 
      if (A <= 74) 
      { 
       e.Row.Cells[2].BackColor = System.Drawing.Color.Red; 
      } 
     } 
    } 
+1

我会看看根据条件创建要设置的颜色枚举。用enum.color drv替换system.Drawing.Color.Red也必须进行更改,否则将不得不创建一个数组或列表或枚举值,以确定哪些字段将被更改。即使它是.config驱动..例如什么是一些业务规则.. ?? – MethodMan 2012-01-12 17:30:47

回答

2
public void SetColor(DataGridViewRow row, string columnName, int cellIndex) 
{ 
    var data = (GridViewRow)row.DataItem; 
    int number = Convert.ToInt32(data[columnName]); 
    if (number > 74) return; 

    row.Cells[cellIndex].BackColor = Color.Red; 
} 

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType != DataRowType.DataRow) return; 
    SetColor(e, "A", 2); 
} 
+0

我会将该颜色作为参数添加到该方法中,至少因为这是它的名称;) – 2012-01-12 17:38:37

+0

@TimSchmelter可以将这些代码重构为可重用的东西。这一切都取决于预期有多少重用。鉴于该职位和当前代码的背景,我认为这是最适用的解决方案。 – 2012-01-12 17:48:02

1

想通了 - Meckley先生把我在正确的轨道,我的工作(如不雅)解决方案是:

public void SetColor2(GridViewRow row, string columnName, int cellIndex) 
    { 
     if (row.RowType == DataControlRowType.DataRow) 
     { 
      int number = Convert.ToInt32(columnName); 
      if (number == 0) 
      { 
       row.Cells[cellIndex].Text = ""; 
       return; 
      } 
      else if ((number > 0) && (number <= 74)) 
      { 
       row.Cells[cellIndex].BackColor = System.Drawing.Color.Red; 
       row.Cells[cellIndex].ForeColor = System.Drawing.Color.Black; 
       return; 
      } 
     } 
    } 

用法:

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.DataItem != null) 
     { 
      DataRowView drv = (DataRowView)e.Row.DataItem; 
      SetColor2(e.Row, drv["A"].ToString(), 2); 
      SetColor2(e.Row, drv["B"].ToString(), 3); 
      etc... 
     } 
    }