Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello

i have a datatable which contain some record. the datatable column are (ID,NAME,CONTACT)
Now i wanted to find the Name and Contact by providing the ID.


suppose select NAME , CONTACT where ID = 1.

What I have tried:

here i have finded the data row of that datatable. like below

DataRow[] dr = dt.Select("ID= 1");


but how to get the NAME and CONTACT number from Datarow[]
Posted
Updated 17-Dec-18 20:12pm

DataRow[] dr = dt.Select("ID= 1");

foreach(DataRow row in dr)
{
    var name = row["NAME"].ToString();
    var contact = row["CONTACT"].ToString();
}
Using the 'Field extension method in System.Data, we can make simpler the casting of Column values from 'object to their native Type:
DataRow[] dr = dt.Select("ID= 1");

foreach(DataRow row in dr)
{
    string name = row.Field<string>("NAME");
    string contact = row.Field<string>("CONTACT");
}
You really need to review the "basics" of using a DataTable: [^], [^].
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 21-Aug-17 6:03am    
5
Considering ID is unique you will always get a single row, so, you do not really need to loop :), just use datarow array with index as 0 to get the NAME and CONTACT like below.

DataRow[] dr = dt.Select("ID= 1");
var name = dr[0]["NAME"].ToString();
var contact = dr[0]["CONTACT"].ToString();
 
Share this answer
 
Comments
BillWoodruff 18-Aug-17 5:16am    
"Considering ID is unique" what makes you certain of this ?
Atlapure Ambrish 18-Aug-17 10:18am    
Ideally, the databases are designed that way.. :)
Richard Deeming 18-Aug-17 10:10am    
If the ID doesn't exist in the table, you'll get an IndexOutOfRangeException. You need to check the Length of the returned array before trying to access the first element.
Atlapure Ambrish 18-Aug-17 10:19am    
My brother, I would leave defensive coding part to the author :)
Member 11203491 18-Dec-18 2:13am    
Thank you so much the solution 2 works like a charm.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900