Saturday, May 30, 2009

Using Viewstate for Saving datatable in asp.net c#

Using a viewstate to save a datatable is useful for developting shopping cart applications. In such a case we have to keep track of all the products that has been selected by the customer on a particular session. For this we use a combination of view state or session to hold the product information in datatable.

Creating a DataTable and saving it on the view state :

private void createMyDataTable()
{

DataTable dtCart = new DataTable();
DataColumn dc = new DataColumn();
DataColumn dc1 = new DataColumn();
DataColumn dc2 = new DataColumn();

dc.DataType = Type.GetType("System.Int32");
dc.ColumnName = "Id";
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dtCart.Columns.Add(dc);
dc1.DataType = Type.GetType("System.String");
dc1.ColumnName = "ProductName";
dtCart.Columns.Add(dc1);
dc2.DataType = Type.GetType("System.Int32");
dc2.ColumnName = "Price";
dtCart.Columns.Add(dc2);

ViewState["dtMyCart"] = dtCart;

}
from the above code we can create a structure of a datatable which can hold the information of the products selected by the client. Once the structure of the table is created we have to save the datatable to a viewstate object. This is done to acess the table later in the page.

Once the datatable structure is saved on our viewstate, we can start using the datatable for saving products. Procedure for adding a new product is as follows

private void addDataToMyTable(string paramProductName, int paramProductId, Int32 paramPrice)
{
MyNewDataTable = (DataTable)ViewState["dtMyCart"];
DataRow row;
row = MyNewDataTable.NewRow();
row["ProductName"] = paramProductName;
row["Id"] = paramProductId;
row["Price"] = paramPrice;


MyNewDataTable.Rows.Add(row);
ViewState["dtMyCart"] = MyNewDataTable;

}

Here in this function, we have four parameters each one has a value for the product. First of all we have to create an instance of the datatable from the viewstate after that we can start adding the product into the user cart.


with regards,
Praveen

No comments:

Post a Comment