[英]How can I color rows in datagridview with condition C#
I want with a condition : 我想要一个条件:
bool_badge =0
: color with RED bool_badge =0
:颜色为红色 bool_badge=1
: color with ForestGreen bool_badge=1
:使用ForestGreen进行颜色 I have a code Correct BUT just when i click for a cell specific 当我单击特定于单元格时,我有一个代码正确但
My code: 我的代码:
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
int row = this.dataGridView1.CurrentCell.RowIndex;
string valeur = dataGridView1[2, row].Value.ToString();
if (valeur == "0")
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
}
else
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
}
}
But I want when i execute my application , the test begin if bool_badge 0 or 1, and i have for all the gridview : color RED or ForestGreen , 但是我想要当我执行我的应用程序时,如果bool_badge为0或1,并且所有网格视图都为我,则测试开始:颜色RED或ForestGreen,
I try this code: 我尝试以下代码:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string valeur = dataGridView1[2, i].Value.ToString();
if (valeur == "0")
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
}
else
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
}
}
But i have ERROR! 但是我有错误!
this is : 这是 :
How can i fix it? 我该如何解决?
Very thanks, 很感谢,
您应该使用.Rows和.Cells属性。
string valeur = dataGridView1.Rows[i].Cells[2].Value.ToString();
You can use Datagridview's Cell_Formatting
event. 您可以使用Datagridview的
Cell_Formatting
事件。
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "bool_badge" && dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
// if the column is bool_badge and check null value for the extra row at dgv
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "0")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.ForestGreen;
}
}
}
Result will be, 结果将是
Hope helps, 希望有帮助,
For helping you debugging don't do Value.ToString(); 为了帮助您调试,请不要执行Value.ToString();。 just
只是
var value = dataGridView_XXX.Rows[rowNumber].Cells[i].value;
And 和
if (value == null) display your row/column index
else dataGridView_XXX.Rows[rowNumber].DefaultCellStyle.BackColor = xxx;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.