我有两个datagridview。 使用相同的列标题但不同的单元格数据。
第一个叫做grid_db 第二个是calld grid_statement。
如果grid_db的值与单元格[j]的grid_statement的值不同,则必须突出显示单元格(红色)。 我尝试了以下
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++;
}
}
但它不起作用。上面的代码突出显示了两个网格的所有列。 帮忙?
答案 0 :(得分:0)
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;
答案 1 :(得分:0)
我尝试了你的代码,它对我有用,我唯一改变的是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;
}
}
}