|
Managing Data with ADO.NET DataSets and C# |
|
Page 2 of 4
Iterating through the DataSet:
Here is a simple code to iterate through the dataset and select individual items instead of selecting all the data in the DataSet.
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROm Categories",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Categories");
DataTable dt = ds.Tables["Categories"];
Response.Write(dt.Rows[0][1].ToString()) ;
1) First few lines are identical which we have done before.
2) In the forth line we declared the DataTable object. DataTable object is used to hold a single table. As I already told you that dataset can hold multiple tables depending upon the query so we can assign a single table from the dataset to the datatable object. I have done that using the line.
DataTable dt = ds.Tables["Categories"];
3) Next we are printing the first row of the second column. Always remember that the number of the rows and columns in the database does not start with 1 but it starts at 0. So in this line of code:
Response.Write(dt.Rows[0][1].ToString()) ;
This line of code means that get Row '0' and Column 1 of the from the datatable. And so we get the value and it prints out "Beverages".
Saving dataSets in Session State:
DataSets can also be saved in the Session State so that it can be available in other areas of the application and in new pages. The way of storing the DataSet in Session State is very easy.
Session["MyDataSet"] = DataSet;
Later if you want to retrieve the DataSet from the Session State you can easily do this by using this line of code:
DataSet ds = (DataSet) Session["MyDataSet"]
As you can see that when I am retrieving the values from the Session object I am casting it into the dataset object. This is because this is explicit conversion and requires casting. I am unboxing in this case.
|