Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Retrieving value from DataTable using PrimaryKey

I have a issue with my code in C#. I have set up a couple of DataTables with a primary key assigned to each of them. what I want to do is to retrieve a single row from a single column.

Lets say I have this code:

DataColumn Pcolumn = new DataColumn();
DataColumn[] key = new DataColumn[1];

Pcolumn.DataType = System.Type.GetType("System.Double");

Pcolumn.ColumnName = "length";
key[0] = Pcolumn;


table6F.Columns.Add(Pcolumn);
table6F.Columns.Add("Area", typeof(double));
table6F.Columns.Add("load", typeof(double));
table6F.Columns.Add("weigth", typeof(double));

table6F.PrimaryKey = key;
table.Rows.Add(6.0, 14.0, 17.8 , 11.0 );
table.Rows.Add(7.0, 16.2 , 20.7 , 16.0 );

And I want to retrieve the the "load" for the second row (20.7), I would like to search for 7.0, primary key column, in the Table. I dummy tested to do like this, just to test:

Object oV;
double load;

//Get an Table object given the specific row number, this dummy i always set to 0.
// Given Column
oV = table.Rows[0]["load"];
load = Convert.ToDouble(oV.ToString());

Is there a similar way to extract using the Primary key?

like image 745
erikduvet Avatar asked Feb 14 '12 09:02

erikduvet


1 Answers

You can retrieve a row from a DataTable based on its primary key using the DataRowCollection.Find method. In your case it would be:

DataRow matchingRow = table.Rows.Find(7.0D);
double value = (double)matchingRow["load"];
like image 108
Enrico Campidoglio Avatar answered Sep 27 '22 17:09

Enrico Campidoglio