Datagridview Cell Backcolor formatting
本文关键字:formatting Backcolor Cell Datagridview | 更新日期: 2023-09-27 18:18:14
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/4cswcoi want to如果单元格值为true,我想将背景颜色更改为绿色否则为红色
我从这个链接中获取了代码;
使用自定义对象的动态列表,并且不能动态更改dataGrid's单元格属性
Please help my question
当使用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;
}
}
}
}