On this post I will show you ,how to add a table to a session and even add a new record, just like a Shopping cart in online shopping websites.
Here is a sample code for adding a table to a session and then rebinding it just like in shopping carts
private void GetData()
{
try
{
DataRow[] dr = null; if (ViewState["SelectedRecords"] != null)
{
dt = (DataTable)ViewState["SelectedRecords"];
}
else
{
dt = CreateDataTable(); 1:
}
2
CheckBox chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
3.this is your main method on how to add or remove items in your datatable, in this example I bound it to a gridview, which have a checkbox for adding or deleting items, this depends on the button clicked
ViewState["SelectedRecords"] = dt;
dtall = dt.Copy();
Session["CombineRecord"] = dtall;
}
catch (Exception ex)
{
}
1: means create a datatable
here is the code for creating a datatable
private DataTable CreateDataTable()2: this part shows what is the behavior if the checkbox is selected and what button is clicked, either add or remove,
{
DataTable dt = new DataTable();
dt.Columns.Add("ItemCode");
dt.Columns.Add("ItemDesc");
dt.AcceptChanges();
return dt;
}
3: this part shows after selecting after modifying the datatable, you will then pass it to the viewstate named selectedrecords to hold it,
then dtall=dt.copy(); means that all records in the datatable dt is copied and moved to datatable named dtall
where dtall will either have an existing record or a new record
then pass dtall datatable to a session variable so that it will not be disposed after
After this,
convert to datatable the session variable and bind it to your gridview.
private void BindSecondaryGrid()
{
gvCart.DataSource = (DataTable)Session["CombineRecord"];
gvCart.DataBind();
}
This summarizes the passing of values to a session just like in Shopping cart
No comments:
Post a Comment