Save temporary values in gridview to database
how to use a DataTable as a temporary storage table in ASP.Net for
storing the records that we need for processing in ViewState or Session
variables.
The concept is to create a dynamic DataTable, store some values in it and then keep the DataTable either in ViewState or Session depending on whether you want it only on the page or throughout the application respectively.
In order to illustrate this concept I will make use an ASP.Net GridView control on which I’ll perform Edit and Update operations and the save the updated data with the temporary DataTable.
The concept is to create a dynamic DataTable, store some values in it and then keep the DataTable either in ViewState or Session depending on whether you want it only on the page or throughout the application respectively.
In order to illustrate this concept I will make use an ASP.Net GridView control on which I’ll perform Edit and Update operations and the save the updated data with the temporary DataTable.
The following HTML Markup consists of an ASP.Net GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowEditing="OnRowEditing">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
ViewState["dt"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
0 Comments