突出显示c#中具有不同值的datagridview单元格
本文关键字:datagridview 单元格 显示 | 更新日期: 2023-09-27 18:29:34
我有两个数据网格视图。具有相同的列标题但不同的单元格数据。
第一个被称为griddb第二个是calld-gridstatement。
如果grid_db的值与单元格[j]处的grid_dtatement的值不同,则我必须突出显示单元格(红色)。我试了以下
int no_of_col = grid_db.Columns.Count;
int j;
for (j = 0; j < no_of_col;)
{
//if statement value is null replace with ZERO
if (grid_statement.Rows[0].Cells[j].Value != null &&
!string.IsNullOrWhiteSpace(grid_statement.Rows[0].Cells[j].Value.ToString()))
{
B = grid_statement.Rows[0].Cells[j].Value.ToString();
}
//if db value is null replace with zero
if (grid_db.Rows[0].Cells[j].Value != null &&
!string.IsNullOrWhiteSpace(grid_db.Rows[0].Cells[j].Value.ToString()))
{
A = grid_db.Rows[0].Cells[j].Value.ToString();
}
if (A != B)
{
grid_db.Rows[0].Cells[j].Style.BackColor = Color.Red;
grid_statement.Rows[0].Cells[j].Style.BackColor = Color.Red;
j++;
}
}
但它不起作用。上面的代码高亮显示了两个轴网的所有列。帮助
我试过你的代码,它对我有效,我唯一改变的是for循环在每次通过时递增,否则它很容易是无限的(它只对第一行有效,因为这就是你的代码所做的):
public Form1()
{
InitializeComponent();
grid_db.DataSource = new[]
{
new{
id = 1,
tekst="a"
},
new
{
id=2,
tekst="b"
}
}.ToList();
grid_statement.DataSource = new[]
{
new{
id = 1,
tekst="b"
},
new
{
id=2,
tekst="c"
}
}.ToList();
Load += (sender, args) =>
{
HighlightRows();
};
}
private void HighlightRows()
{
int no_of_col = grid_db.Columns.Count;
int j;
var B = "";
var A = "";
for (j = 0; j < no_of_col; j++)
{
//if statement value is null replace with ZERO
if (grid_statement.Rows[0].Cells[j].Value != null &&
!string.IsNullOrWhiteSpace(grid_statement.Rows[0].Cells[j].Value.ToString()))
{
B = grid_statement.Rows[0].Cells[j].Value.ToString();
}
//if db value is null replace with zero
if (grid_db.Rows[0].Cells[j].Value != null &&
!string.IsNullOrWhiteSpace(grid_db.Rows[0].Cells[j].Value.ToString()))
{
A = grid_db.Rows[0].Cells[j].Value.ToString();
}
if (A != B)
{
grid_db.Rows[0].Cells[j].Style.BackColor = Color.Red;
grid_statement.Rows[0].Cells[j].Style.BackColor = Color.Red;
}
}
}
var differentCells =
grid_db.Rows.OfType<DataGridViewRow>()
.SelectMany(r=>r.Cells.OfType<DataGridViewCell>())
.Where(c=>!grid_statement[c.ColumnIndex,c.RowIndex].Value.Equals(c.Value));
//loop through all the cells and make them red
foreach(var cell in differentCells)
cell.Style.BackColor = Color.Red;