我在比较datagridviews方面遇到了问题。我需要比较2个datagridviews,如果值相同,请标记它们或做一些事情。 (我从excel导入值)
我不能使用linq它很慢。
我试试这个,但似乎我无法让它起作用:
for (int currentRow = 0; currentRow < grv.Rows.Count; currentRow++)
{
var rowToCompare = grv.Rows[currentRow]; // Get row to compare against other rows
// Iterate through all rows
//
foreach (var row in grv.Rows)
{
if (rowToCompare.equals(row) continue; // If row is the same row being compared, skip.
bool duplicateRow = true;
// Compare the value of all cells
//
for (int cellIndex; cellIndex < row.Cells.Count; cellIndex++)
{
if (!rowToCompare.Cells[cellIndex].Value.equals(row.Cells[cellIndex].Value))
{
duplicateRow = false;
break;
}
}
if (duplicateRow)
{
grv.Rows.Remove(row);
}
}
}
答案 0 :(得分:0)
试试这个:
private void button1_Click(object sender, EventArgs e)
{
DataTable src1 = grv1.DataSource as DataTable;
DataTable src2 = grv2.DataSource as DataTable;
int index1 = 0;
foreach (DataRow row1 in src1.Rows)
{
foreach (DataRow row2 in src2.Rows)
{
int index2 = 0;
bool duplicateRow = true;
for (int cellIndex = 0; cellIndex < row1.ItemArray.Count(); cellIndex++)
{
if (!row1.ItemArray[cellIndex].ToString().Equals(row2.ItemArray[cellIndex].ToString()))
{
duplicateRow = false;
break;
}
}
if (duplicateRow)
{
grv1.Rows[index1].DefaultCellStyle.BackColor = Color.Red;
grv2.Rows[index2].DefaultCellStyle.BackColor = Color.Red;
}
index2++;
}
index1++;
}
}
这应该用红色复制颜色。确保两个gridview具有相同的单元格编号。
答案 1 :(得分:0)
private void button5_Click(object sender, EventArgs e)
{
DataTable src1 = dataGridView1.DataSource as DataTable;
DataTable src2 = dataGridView2.DataSource as DataTable;
for (int i = 0; i < src1.Rows.Count; i++)
{
var row1 = src1.Rows[i].ItemArray;
var row2 = src2.Rows[i].ItemArray;
for (int j = 0; j < row1.Length; j++)
{
if (!row1[j].ToString().Equals(row2[j].ToString()))
{
dataGridView1.Rows[i].Cells[j].Style.BackColor = Color.Red;
dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Red;
}
}
}
这将突出显示具有相同值的单元格。如果datagridviews都应具有相同的行数。