Datagridview Cell Backcolor格式

时间:2014-08-14 18:18:42

标签: c# datagridview formatting cell

 foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                string kesim = Convert.ToString(row.Cells["kesim"].Value);

                if (kesim == "True")
                {


                    dataGridView1.Rows[row.Index].Cells["kesim"].Style.BackColor = Color.Green;
                    dataGridView1.Rows[row.Index].Cells["kesim"].ReadOnly = true;
                    dataGridView1["kesim", row.Index].ReadOnly = true;
                    dataGridView1["kesim", row.Index].Style.BackColor = Color.Green;          
                 }
               else
                {

                    dataGridView1.Rows[row.Index].Cells["kesim"].Style.BackColor = Color.Red;
                    dataGridView1.Rows[row.Index].Cells["kesim"].ReadOnly = true;
                    dataGridView1["kesim", row.Index].ReadOnly = true;
                    dataGridView1["kesim", row.Index].Style.BackColor = Color.Red;      
                }
                string torna = Convert.ToString(row.Cells["torna"].Value);

                if (torna == "True")
                {


                    dataGridView1.Rows[row.Index].Cells["torna"].Style.BackColor = Color.Green;
                    dataGridView1.Rows[row.Index].Cells["torna"].ReadOnly = true;
                    dataGridView1["torna", row.Index].ReadOnly = true;
                    dataGridView1["torna", row.Index].Style.BackColor = Color.Green;
                }
              else
                {


                    dataGridView1.Rows[row.Index].Cells["torna"].Style.BackColor = Color.Red;
                    dataGridView1.Rows[row.Index].Cells["torna"].ReadOnly = true;
                    dataGridView1["torna", row.Index].ReadOnly = true;
                    dataGridView1["torna", row.Index].Style.BackColor = Color.Red;
                }
            }

我的第一行;

http://prntscr.com/4csw89

我的第二排;

http://prntscr.com/4cswco

我想如果单元格值为true,我想将背面颜色更改为绿色,否则为红色。

我从这个链接中获取了代码;

Using a dynamic list of Custom Object and can't dynamically change dataGrid's cells properties

请帮助我提问

1 个答案:

答案 0 :(得分:1)

使用CellFormatting事件时,您不必遍历所有行,因为该事件将为您提供正在修改的单元格的ColumnIndex和RowIndex。只需格式化需要格式化的单元格:

void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
  if (e.Value != null) {
    if (dgv.Columns[e.ColumnIndex].Name == "kesim" | 
        dgv.Columns[e.ColumnIndex].Name == "torna" ) {
      if (e.Value.ToString() == "True") {
        e.CellStyle.BackColor = Color.Green;
      } else {
        e.CellStyle.BackColor = Color.Red;
      }
    }
  }
}