如何使用条件C#在datagridview中对行进行排序 [英] How can I color rows in datagridview with condition C#
本文介绍了如何使用条件C#在datagridview中对行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个条件:
- 所有行都有
bool_badge = 0
:颜色与 RED - 所有行都有
bool_badge = 1
:color with ForestGreen
- all rows have
bool_badge =0
: color with RED - all rows have
bool_badge=1
: color with ForestGreen
我有一个代码正确但是当我点击一个单元格
I have a code Correct BUT just when i click for a cell specific
我的代码:
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;
}
}
结果:
1)`
The Result : 1) `
2)
但是,当我执行我的应用程序时,如果bool_badge 0或1,测试开始,我有所有的gridview:color RED或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 ,
我尝试这个代码:
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;
}
}
但我有错误!
这是:
如何解决?
非常感谢,
推荐答案
您可以使用Datagridview的 Cell_Formatting
事件。
You can use Datagridview's Cell_Formatting
event.
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;
}
}
}
strong>将是
Result will be,
希望有帮助,
这篇关于如何使用条件C#在datagridview中对行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文