Compare value between 2 datagridview c# -
i have 2 datagridviews. datagridview1
has 3 rows , datagridview2
has 2 rows.how compare values between them.
exa: datagridview1 datagridview2 id name id name 1 3 c 2 b 4 3 c
i want compare:
1 vs 3, 1 vs 4,
2 vs 3, 2 vs 4,
3 vs 3, 3 vs 4.
i use code below works incorrect.
for (int = 0; < datagridview1.rowcount; i++) { (int j = 0; j < datagridview2.rowcount; j++) { i++; string grid2 = datagridview2.rows[j].cells[1].value.tostring(); string grid1 = datagridview1.rows[i].cells[1].value.tostring(); if (grid1 == grid2 || datagridview2.rows[0].cells[1].value.tostring() == datagridview1.rows[0].cells[1].value.tostring() ) { datagridview1.rows.removeat(i); } } }
1)
if want iterate through collection using loop not wise increment indexing variable additionally in code line:
i++;
it incremented. when run through datagridview2
slide 1 position further in datagridview1
. not want (as see post describe desired comparisons). need remove line
2)
i want compare: 1 vs 3, 1 vs 4, 2 vs 3, 2 vs 4, 3 vs 3, 3 vs 4.
if want compare name
column indexing right :
datagridview2.rows[j].cells[1]
but if want compare id column wrong because indexing starts 0
. correct value id
column have use this:
string grid2 = datagridview2.rows[j].cells[0].value.tostring();
with comparison in if-condition:
datagridview2.rows[0].cells[1].value.tostring() == datagridview1.rows[0].cells[1].value.tostring()
you additionally compare a
c
. don't see reason (taken description comparison desire). can rid of it.
3)
if want change size of collection (by deleting elements) through iterate wise use reversed for-loop starts datagridview2.rowcount-1
, runs until >= 0
. otherwise risk run argumentoutofbounds
exception because don't have elements after removal did when started loop. element @ end index not exist anymore.
for (int = datagridview1.rowcount-1; >= 0 ; i--) { (int j = 0; j < datagridview2.rowcount; j++) { string grid2 = datagridview2.rows[j].cells[0].value.tostring(); string grid1 = datagridview1.rows[i].cells[0].value.tostring(); if (grid1 == grid2) { datagridview1.rows.removeat(i); } } }
edit:
the datagridview1
might display additional empty row counted in datagridview1.rowcount
in case need start i = datagridview1.rowcount-2
. after have found match , removed row datagridview1
not make sense search further matches row, since gone. should break out of inner loop , proceed next line:
for (int = datagridview1.rowcount - 2; >= 0; i--) { (int j = 0; j < datagridview2.rowcount -1; j++) { string grid2 = datagridview2.rows[j].cells[0].value.tostring(); string grid1 = datagridview1.rows[i].cells[0].value.tostring(); if (grid1 == grid2) { datagridview1.rows.removeat(i); break; } } }
wiki
Comments
Post a Comment