In this article I will explain with an example, how to insert data in
GridView without using database in
ASP.Net using C# and VB.Net.
HTML Markup
The following
HTML Markup consists of:
GridView – For displaying data.
Columns
The
GridView consists of two
BoundField column.
TextBox – For insert name and country.
Button – For insert data in
GridView control.
<asp:GridView ID="gvCustomers" runat="server" CssClass="Grid" AutoGenerateColumns="false"
EmptyDataText="No records has been added.">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
</Columns>
</asp:GridView>
<br />
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td style="padding-bottom: 10px">Name:<br />
<asp:TextBox ID="txtName" runat="server" />
</td>
</tr>
<tr>
<td style="padding-bottom: 10px">Country:<br />
<asp:TextBox ID="txtCountry" runat="server" />
</td>
</tr>
<tr>
<td style="width: 100px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
Namespace
You will need to import the following namespace.
C#
VB.Net
Binding the GridView using an Empty DataTable
Here the primary reason to use
ViewState variable is to preserve the
GridView data across
PostBacks.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] {
new DataColumn("Name"),
new DataColumn("Country") });
ViewState["Customers"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
gvCustomers.DataSource = (DataTable)ViewState["Customers"];
gvCustomers.DataBind();
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(1) {
New DataColumn("Name"),
New DataColumn("Country")})
ViewState("Customers") = dt
Me.BindGrid()
End If
End Sub
Protected Sub BindGrid()
gvCustomers.DataSource = DirectCast(ViewState("Customers"), DataTable)
gvCustomers.DataBind()
End Sub
Inserting data in GridView without using database in ASP.Net
First the
DataTable is fetched from the
ViewState variable and then a new Row is added to the
DataTable by making use of the data from the
TextBoxes.
C#
protected void Insert(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["Customers"];
dt.Rows.Add(txtName.Text.Trim(),txtCountry.Text.Trim());
ViewState["Customers"] = dt;
this.BindGrid();
txtName.Text = string.Empty;
txtCountry.Text = string.Empty;
}
VB.Net
Protected Sub Insert(sender As Object, e As EventArgs)
Dim dt As DataTable = DirectCast(ViewState("Customers"), DataTable)
dt.Rows.Add(txtName.Text.Trim(), txtCountry.Text.Trim())
ViewState("Customers") = dt
Me.BindGrid()
txtName.Text = String.Empty
txtCountry.Text = String.Empty
End Sub
Screenshot
Demo
Downloads