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?
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"];
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