I am working on a windows form application. How do i use the find method of a datatable to find a row if the datatable has a compound key?
Table Structure Col A, Col B, Col C
Col A and Col B make up the compound key. I want to find the row where the value in Col A is 6 and Col B is 5
You can use aggregate function count(*). If it returns a value greater than 1, that would mean the table has composite primary key.
In a table representing students our primary key would now be firstName + lastName. Because students can have the same firstNames or the same lastNames these attributes are not simple keys. The primary key firstName + lastName for students is a composite key.
A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).
When you "set" the Primary key of the datatable, the parameter value is an array of DataColumns...
if your datatable is in variable dt...,
dt.PrimaryKey = new DataColumn[] {dt.Columns["ColA"], dt.Columns["ColB"]};
Then pass an array of object values to the Find() method
object[] keyVals = new object[] {6, 5};
DataRow dr = dt.Rows.Find(keyVals);
or, just
DataRow dr = dt.Rows.Find(new object[] {6, 5});
There is an overload that you can use to pass in two different values to the find method. Here is the MSDN doc.
So you would most likely be doing something like.
DataTable.Rows.Find(6,5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With