2013-02-08 31 views
0

我正在创建基于表单和DataGridView控件的应用程序。根据其价值改变单元格样式?

我从数据库绑定信息,现在我想要做的是根据其值可以是"Urgent","Haute","Normale"更改列propeties的字体样式和颜色。

这是我正在使用的代码,但它没有奏效,可能有人告诉我下面的代码出了什么问题?

代码:

private void ColorizeCellsbyValue() { 

     DataGridViewCellStyle BoldRed = null; 
     BoldRed = new DataGridViewCellStyle(); 
     BoldRed.Font = new Font("Tahoma", 9, FontStyle.Bold); 
     BoldRed.ForeColor = Color.Red; 

     DataGridViewCellStyle Red = null; 
     Red = new DataGridViewCellStyle(); 
     Red.ForeColor = Color.Red; 

     DataGridViewCellStyle Black = null; 
     Black = new DataGridViewCellStyle(); 
     Black.ForeColor = Color.Black; 
     string priority; 
     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      priority = row.Cells[3].Value.ToString(); 
      switch (priority) 
      { 
       //Change font 
       case "Urgent": 
        row.Cells[3].Style = BoldRed; 
        break; 
       case "Haute": 
        row.Cells[3].Style = Red; 
        break; 
       case "Normale": 
        row.Cells[3].Style = Black; 
        break; 
       default: 
        row.Cells[3].Style = Black; 
        break; 
      } 
     } 
} 

回答

1

尝试使用

row.Cells[3].Style.BackColor = <Color>; 

ForeColor使用

row.Cells[3].Style.ForeColor = <Color>; 

这应该工作。快乐的编码!

+0

+1可惜OP希望_“更改字体样式” _': D' – spajce 2013-02-08 12:06:18

+0

@spajce已更新为Fore颜色:) – Ravia 2013-02-08 12:56:59

+0

它似乎不想格式化您的答案? ':D' – spajce 2013-02-08 13:02:49

1

您无需创建DataGridViewCellStyle即可设计您的Column属性。揣摩我简单的例子

 foreach (DataGridViewRow rows in dataGridView1.Rows) 
     { 
      if (rows.Cells[3].RowIndex % 2 == 0) 
      { 
       rows.Cells[3].Style.Font = new Font("Tahoma", 9, FontStyle.Bold); 
       rows.Cells[3].Style.BackColor = Color.Red; 
      } 
      else 
      { 
       rows.Cells[3].Style.Font = new Font("Arial", 9, FontStyle.Regular); 
       rows.Cells[3].Style.BackColor = Color.Blue; 
      } 
     } 

,我的回答你的问题主要是尝试使用.EditedFormattedValue.ToString()

 foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      priority = row.Cells[3].EditedFormattedValue.ToString(); 
      switch (priority) 
      { 
       //Change font 
       case "Urgent": 
        row.Cells[3].Style = BoldRed; 
        break; 
       case "Haute": 
        row.Cells[3].Style = Red; 
        break; 
       case "Normale": 
        row.Cells[3].Style = Black; 
        break; 
       default: 
        row.Cells[3].Style = Black; 
        break; 
      } 
     } 
相关问题