Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting data out of a data set

Status
Not open for further replies.

developer155

Programmer
Jan 21, 2004
512
US
Hello I have a dataset and I am trying to find out how to get data from it using individual column name.
here is my code:
SqlConnection cn1 = new SqlConnection();
cn1.ConnectionString="Database=MyDB;User=sa;Password=pass;Server=SomeServ;";
cn1.Open();
SqlDataAdapter da = new SqlDataAdapter("Seelct * from Customers where customerid=111", cn1);
DataSet ds = new DataSet("DataSet");
da.Fill(ds,"DataSet");

So now I have this data from Customers table in dataset and I need to get single fields, like CustomerName, CustomerAddress

What is the way to do this?

thanks alot!!!!
 
ds.Tables[0] is a DataTable that contains the Customers information.
A DataTable objects has a collection of rows and a row is a collection af columns.
So, you can see the DataTable as a matrix and you access a column value providing the row and the column:
Code:
// Access by index
object val = dt.Rows[iRow][iColumn]; // row iRow and column iColumn
// Access by column name
object val1 = dt.Rows[iRow]["CustomerName"];
object val2 = dt.Rows[iRow][CustomerAddress"];
Or, directly from the DataSet object:
Code:
int iRow = 2;
if (ds.Tables.Count >0 && iRow < ds.Tables[0].Rows.Count)
{
   object val = ds.Tables[0].Rows[idx]["CustomerName"];
}
obislavu
 
Since he use only one customer (ID 111) can't he use a datareader to read the single record. I think this is more efficent (unless he is doing any update or delete etc.)
 
Check out the possibility of using Typed Datasets (loads of info on Google), then you can refer to the column name as an object property.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top