C#Datagridview仅根据前1000条记录的条件更改行颜色
我的datagridview有点问题。我正在用数据库中的记录填充Datagridview 但是我想在一个特定的条件下改变背景色和前景色。它工作得很好,但只有前1000条记录,问题是我有超过10000条记录。我做错事情了吗 如果有更好的解决办法,我将不胜感激 致意 我的代码:C#Datagridview仅根据前1000条记录的条件更改行颜色,c#,datagridview,backcolor,C#,Datagridview,Backcolor,我的datagridview有点问题。我正在用数据库中的记录填充Datagridview 但是我想在一个特定的条件下改变背景色和前景色。它工作得很好,但只有前1000条记录,问题是我有超过10000条记录。我做错事情了吗 如果有更好的解决办法,我将不胜感激 致意 我的代码: private void dataView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { foreach(DataGri
private void dataView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach(DataGridViewRow row in dataView.Rows)
{
int value = Convert.ToInt32(row.Cells[2].Value);
if(value == 1)
{
row.DefaultCellStyle.BackColor = Color.Orange;
}
else
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
}
在您的情况下,
CellFormatting
事件不是最好的选择。for循环导致您对数据进行多次迭代
您可以为您的场景使用RowPrePaint
、RowPostPaint
或DataBindingComplete
事件
使用RowPrePaint
将允许您为行着色,并保留打开选项,以便为单个单元格应用其他单元格级别样式
private void dataView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
DataGridViewRow row = dataView.Rows[e.RowIndex];
if (Convert.ToInt32(row.Cells[2].Value) == 1)
{
row.DefaultCellStyle.BackColor = Color.Orange;
}
else
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
如果选择保持循环,则可以使用DataBindingComplete
事件
private void dataView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dataView.Rows)
{
int value = Convert.ToInt32(row.Cells[2].Value);
if (value == 1)
{
row.DefaultCellStyle.BackColor = Color.Orange;
}
else
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
}
@夸巴姆
谢谢你,第一个解决方案对我很有效。我可以用此事件更改2个单元格吗?像这样:
private void DataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
//Secili olanlarin rengini degisdiriyo
if (Convert.ToInt32(row.Cells["Secili"].Value) == 1)
{
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightSalmon;
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
}
else
{
//Aktiv olmiyanlari kirmizi yapiyo
if (Convert.ToInt32(row.Cells["IsActive"].Value) == 1)
{
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
}
else
{
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;
}
}
}
编辑:
我现在有另一个问题。。前1000条记录中的一些被封锁了。我不知道为什么。我正在使用我在这里发布的函数
图像:引发此事件以允许您格式化单元格。每次引发此事件时,您都在循环整个行集合。您只需检查当前的
e.ColumnIndex
是否与您关心的列匹配,并更改相应单元格的背景色。无循环。当前行为dataView.Rows[e.RowIndex]
@Jimi您认为他重复循环集合是正确的,不应该这样做。但他想改变这一行的风格,而不仅仅是他自己。他不应该使用CellFormatting
事件来设置行的样式,他将在调用CellFormatting
事件时重复逻辑来为每个单元格设置行的样式。@Jimi它已经过测试,如果OP想要保持循环,我还提出了databindingplete
事件。@quaabaam,它可以在设置初始状态时工作。如果需要实时应用此格式(当值因其他原因或用户干预而更改时),则需要其他内容。所以,这个事件可能不是真正需要的。无论如何,因为RowPostPaint/RowPrePaint可以工作,所以这就足够了(在绑定数据源时,还可以避免执行两次相同的操作)。