Reputation: 29179
I have a DataGridView which displays the values of the following columns in a table
PK1, PK2, PK3, C1, C2, C3, C4
1, 2, 3, A, B, X, Y
4, 1, 4, C, D, Z, Y (Match the rows in the table below)
2, 3, 5, F, E, X, W
3, 1, 2, A, B, X, Y (Match the rows in the table below)
......
PK1, PK2, PK3
are combined Primary Key of the table. Given a DataTable of the PKs (The example is shown below). What's the best approach to find these rows?
PK1, PK2, PK3
4, 1, 4
3, 1, 2
(iterate DataGridView cells or underline DataSource? Maybe cells since I will need to highlight some cells in the rows. Performance considerations?)
Upvotes: 0
Views: 219
Reputation: 632
You can define DataTable.PrimaryKey()
and then use DataTable.Rows.Find()
.
Working on datatable is more efficient than DataGridView Cell. I recomend taking care before formating cells, check this Using Cell Styles Efficiently .
Upvotes: 0
Reputation: 383
I would take a look at the DataGridView RowPrePaint event, CellFormatting event, or CellPainting event, to implement the highlighting.
For matching the rows, it kind of matters where the data is coming from. If it's coming from the same database, could you do the matching in the query that returns the data? You could use Linq to do a query on the DataTables and find the matches.
Another idea would be to create a DataRelation between your two DataTables. See the example on the DataTable Class page, near the bottom. Search on MakeDataRelation
to find the example. DataRelations can be really tricky, but when you get them working, they're really cool.
To evaluate performance considerations, more information is probably needed. Where is the data coming from? How many rows of data in each table, a few, 10s, 100s, 1000s? Do you have any control over the design of your data source? Could you eliminate this composite key and create a surrogate key?
If you have control over the query, you could do something like:
SELECT A.PK1, A.PK2, A.PK3, A.C1, A.C2, A.C3,
WHEN B.PK1 IS NULL THEN 0 ELSE 1 END AS OTHER
FROM TABLEA AS A
LEFT JOIN TABLEB AS B ON A.PK1 = B.PK1 AND A.PK2 = B.PK2 AND A.PK3 = B.PK3
WHERE <whatever other criteria you have for this query>
Now the OTHER column in the DataTable would indicate if TableB had a match. You don't really need the WHEN...END
clause, you could just put B.PK1
and deal with null versus a value, assuming that PK1
would never have a valid value of null. In your application, don't display the OTHER
column, just use it as the value that determines whether to do the highlighting or not.
Upvotes: 1