Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value from a DataSet into a variable

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.

like image 323
kalls Avatar asked Sep 02 '11 14:09

kalls


3 Answers

// 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]);
}
like image 62
Damith Avatar answered Oct 13 '22 12:10

Damith


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");
like image 40
samack Avatar answered Oct 13 '22 12:10

samack


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.

like image 39
James Johnson Avatar answered Oct 13 '22 13:10

James Johnson