I have the following method which returns dataset. I am using .NET 2.0
DataSet ds = GetAllRecords();
I want to get values from each column for a particular row and bind it to a variable. How can this be achieved?
currently the method returns all the row from the table and I have to find that particular row based on ID.
However, if that is not possible I can come with
DataSet ds = GetSpecificRecord(id);
But I still need to get values from each column and bind it to variable. Please advice.
// Create a table
DataTable table = new DataTable("users");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));
table.Rows.Add(1, "abc");
table.Rows.Add(2, "ddd");
table.Rows.Add(3, "fff");
table.Rows.Add(4, "hhh d");
table.Rows.Add(5, "hkf ds");
// Search for given id e.g here 1
DataRow[] result = table.Select("Id = 1"); // this will return one row for above data
foreach (DataRow row in result)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
This will get you the value from Row 0 obviously you would need to modify for multiple rows returned
long id = ds.Tables[0].Rows[0].Field<long>("ID");
You can do this with LINQ.
DataRow resultRow = ds.Tables["SomeTable"].AsEnumerable().Where(row => row.Field<int>("SomeID") == 1).FirstOrDefault();
For .NET 2.0 and below
If your DataTable has a primary key defined, you can find the row like this:
DataTable table = ds.Tables["SomeTable"];
DataRow row = table.Rows.Find(1);
If there is no primary key, you can assign one like this:
DataTable table = ds.Tables["SomeTable"];
table.PrimaryKey = new DataColumn[] { table.Columns["SomeID"] };
DataRow row = table.Rows.Find(1);
Another option is to use the RowFilter property of the DefaultView, like this:
DataTable table = ds.Tables["SomeTable"];
table.DefaultView.RowFilter = "SomeID == 1"; //not sure if it's == or = here
DataRow row = table.DefaultView[0].Row;
Lastly, you can also use the DataTable.Select() method to find rows.
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