Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the find method of a datatable with a compound key?

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

like image 660
Kalel Avatar asked Nov 24 '08 17:11

Kalel


People also ask

How do I find composite keys in SQL?

You can use aggregate function count(*). If it returns a value greater than 1, that would mean the table has composite primary key.

What is an example of a composite key in a database table?

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.

Can a table have both primary key and 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).


2 Answers

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});
like image 123
Charles Bretana Avatar answered Sep 27 '22 21:09

Charles Bretana


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)
like image 22
Mitchel Sellers Avatar answered Sep 27 '22 21:09

Mitchel Sellers