Hi akhter,
Check this sample now take its reference and correct your code.
HTML
<asp:ScriptManager ID="scriptManager1" runat="server" />
<asp:UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
Name :<asp:TextBox ID="txtName" runat="server" /><br />
Country :<asp:TextBox ID="txtCountry" runat="server" /><br />
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="OnSave" /><br /><br />
<asp:GridView runat="server" ID="gvCustomers">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Namespaces
C#
using System.Data;
VB.net
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (ViewState["dt"] != null)
{
this.BindCustomers();
}
}
}
protected void OnSave(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (ViewState["dt"] == null)
{
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(txtName.Text.Trim(), txtCountry.Text.Trim());
ViewState["dt"] = dt;
}
else
{
dt = ViewState["dt"] as DataTable;
dt.Rows.Add(txtName.Text.Trim(), txtCountry.Text.Trim());
}
this.BindCustomers();
this.txtName.Text = string.Empty;
this.txtCountry.Text = string.Empty;
}
private void BindCustomers()
{
this.gvCustomers.DataSource = ViewState["dt"] as DataTable;
this.gvCustomers.DataBind();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
If ViewState("dt") IsNot Nothing Then
Me.BindCustomers()
End If
End If
End Sub
Protected Sub OnSave(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As DataTable = New DataTable()
If ViewState("dt") Is Nothing Then
dt.Columns.AddRange(New DataColumn() {New DataColumn("Name"), New DataColumn("Country")})
dt.Rows.Add(txtName.Text.Trim(), txtCountry.Text.Trim())
ViewState("dt") = dt
Else
dt = TryCast(ViewState("dt"), DataTable)
dt.Rows.Add(txtName.Text.Trim(), txtCountry.Text.Trim())
End If
Me.BindCustomers()
Me.txtName.Text = String.Empty
Me.txtCountry.Text = String.Empty
End Sub
Private Sub BindCustomers()
Me.gvCustomers.DataSource = TryCast(ViewState("dt"), DataTable)
Me.gvCustomers.DataBind()
End Sub
Screenshot