C#变色一个行如果它不为空 [英] c# change color for a row if its not empty
问题描述
我有一个表上的某些值。如果行单元格Name不是背景紫色的空变色。
名称标识客户
尼奇1是//此处更改背景紫色
2没有
唐娜3是//此处更改背景紫色
巴卡4没有//此处更改背景紫色
5是
6没有
我曾尝试这个代码,但我不工作,不知道为什么
的foreach(在dataGridView1.Rows的DataGridViewRow ROW1)
{
如果(row1.Cells [0 !] .value的= NULL)
{
row1.DefaultCellStyle.BackColor = Color.Violet;
}
}
的老地方把这种如果代码中的 DataBindingComplete
事件处理程序中,无论是附加的事件如下或使用设计器:
dataGridView1.DataBindingComplete + =新DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
然后在处理程序中,你有这样的事情:
无效dataGridView1_DataBindingComplete(对象发件人,DataGridViewBindingCompleteEventArgs E)
{
的foreach(的DataGridViewRow ROW1在dataGridView1.Rows)
{
如果(row1.Cells.Cast< DataGridViewCell的方式>()任何(C => c.Value == NULL || string.IsNullOrWhiteSpace(c.Value.ToString())))
{
ROW1 .DefaultCellStyle.BackColor = Color.Violet;
}
,否则
{
row1.DefaultCellStyle.BackColor = Color.White;
}
}
}
在上面我代码已经改变了原来的代码,现在看起来在所有细胞,而不仅仅是第一个。
您也可以将代码放在在CellFormatting事件。
I have a table an some values on it. If the Row Cell "Name" is not empty change color of background to violet.
Name ID Customers
Niky 1 yes // here change background to violet
2 no
Donna 3 yes // here change background to violet
Baka 4 no // here change background to violet
5 yes
6 no
I have tried this code but i doesnt work, dont know why:
foreach (DataGridViewRow row1 in dataGridView1.Rows)
{
if (row1.Cells[0].Value != null)
{
row1.DefaultCellStyle.BackColor = Color.Violet;
}
}
The usual place to put this sort if code in within the DataBindingComplete
event handler, either attach the event as below or using the designer:
dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
Then in the handler you have something like this:
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row1 in dataGridView1.Rows)
{
if (row1.Cells.Cast<DataGridViewCell>().Any(c => c.Value == null || string.IsNullOrWhiteSpace(c.Value.ToString())))
{
row1.DefaultCellStyle.BackColor = Color.Violet;
}
else
{
row1.DefaultCellStyle.BackColor = Color.White;
}
}
}
In the code above I've changed your original code to now looks at all cells rather than just the first.
You can also put the code in the CellFormatting event.
这篇关于C#变色一个行如果它不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!