Skip to main content

Add record to Database using ASP.Net GridView EmptyDataTemplate and FooterTemplate


In this article I will explain how to insert new records to SQL Server database using ASP.Net GridView’s Empty Data Template.
Database
The below screenshot displays the structure of the database table that will store the customer records
Add new record to Empty GridView using EmptyDataTemplate

HTML Markup
Below is the HTML Markup of the ASP.Net GridView control
<asp:GridView ID="GridView1" runat="server" Width="550px" AutoGenerateColumns="false"
    AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green" ShowFooter="true">
    <Columns>
        <asp:TemplateField HeaderText="Customer Name">
            <ItemTemplate>
                <%# Eval("CustomerName"%>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtCustomerName" runat="server" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Company Name">
            <ItemTemplate>
                <%# Eval("CompanyName"%>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtCompanyName" runat="server" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City">
            <ItemTemplate>
                <%# Eval("City"%>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
            </ItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" CommandName = "Footer" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
    <AlternatingRowStyle BackColor="#C2D69B" />
    <EmptyDataTemplate>
        <tr style="background-color: Green;">
            <th scope="col">
                Customer Name
            </th>
            <th scope="col">
                Company Name
            </th>
            <th scope="col">
                City
            </th>
            <th scope="col">
                   
            </th>
        </tr>
        <tr>
            <td>
                <asp:TextBox ID="txtCustomerName" runat="server" />
            </td>
            <td>
                <asp:TextBox ID="txtCompanyName" runat="server" />
            </td>
            <td>
                <asp:TextBox ID="txtCity" runat="server" />
            </td>
            <td>
                <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" CommandName ="EmptyDataTemplate" />
            </td>
        </tr>
    </EmptyDataTemplate>
</asp:GridView>
 
Above you will notice that the ASP.Net GridView is displaying 3 columns, Customer Name, Company Name and City. I have added textboxes and button to add new records in the <FooterTemplate> and <EmptyDataTemplate>.
 
Binding the GridView
Below is the code to bind the data from the SQL Server database to the ASP.Net GridView control
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindData();
    }
}
 
private void BindData()
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        string strQuery = "SELECT * FROM Customers";
        SqlCommand cmd = new SqlCommand(strQuery);
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgsHandles Me.Load
    If Not IsPostBack Then
       Me.BindData()
    End If
End Sub
 
Private Sub BindData()
    Dim dt As DataTable = New DataTable
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
    Using con As SqlConnection = New SqlConnection(strConnString)
       Dim strQuery As String = "SELECT * FROM Customers"
       Using cmd As SqlCommand = New SqlCommand(strQuery)
             Dim sda As SqlDataAdapter = New SqlDataAdapter
             cmd.Connection = con
             con.Open()
             sda.SelectCommand = cmd
             sda.Fill(dt)
             GridView1.DataSource = dt
             GridView1.DataBind()
       End Using
    End Using
End Sub
 
The below screenshot displays GridView when there is no data in the database, you will notice that it is displaying the<EmptyDataTemplate> with three textboxes and a button.
Add new record to Empty GridView using EmptyDataTemplate

Add new record to database using GridView
Below is the code that gets called when the Add button is clicked. This code snippet fires an insert query in the database and inserts the record in the SQL Server database table
C#
protected void Add(object sender, EventArgs e)
{
    Control control = null;
    if (GridView1.FooterRow != null)
    {
        control = GridView1.FooterRow;
    }
    else
    {
        control = GridView1.Controls[0].Controls[0];
    }
    string customerName = (control.FindControl("txtCustomerName"as TextBox).Text;
    string companyName = (control.FindControl("txtCompanyName"as TextBox).Text;
    string city = (control.FindControl("txtCity"as TextBox).Text;
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT INTO [Customers] VALUES(@CustomerName, @CompanyName, @City)";
            cmd.Parameters.AddWithValue("@CustomerName", customerName);
            cmd.Parameters.AddWithValue("@CompanyName", companyName);
            cmd.Parameters.AddWithValue("@City", city);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}
 
VB.Net
Protected Sub Add(ByVal sender As ObjectByVal e As EventArgs)
    Dim control As Control = Nothing
    If (Not (GridView1.FooterRow) Is NothingThen
        control = GridView1.FooterRow
    Else
        control = GridView1.Controls(0).Controls(0)
    End If
    Dim customerName As String = CType(control.FindControl("txtCustomerName"), TextBox).Text
    Dim companyName As String = CType(control.FindControl("txtCompanyName"), TextBox).Text
    Dim city As String = CType(control.FindControl("txtCity"), TextBox).Text
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
    Using con As SqlConnection = New SqlConnection(strConnString)
        Using cmd As SqlCommand = New SqlCommand
            cmd.Connection = con
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "INSERT INTO [Customers] VALUES(@CustomerName, @CompanyName, @City)"
            cmd.Parameters.AddWithValue("@CustomerName", customerName)
            cmd.Parameters.AddWithValue("@CompanyName", companyName)
            cmd.Parameters.AddWithValue("@City", city)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            Response.Redirect(Request.Url.AbsoluteUri)
       End Using
   End Using
End Sub
 
Above after the record is inserted in the database, the page is redirected to itself so that GridView is loaded with the newly inserted record. The below screenshot displays the GridView with the newly added record and now it is displaying the <FooterTemplate> with three textboxes and add button.

Add new record to Empty GridView using EmptyDataTemplate

Downloads
You can download the sample source code in VB.Net and C# along with the Database script using the download link provided below
Add Records to ASP.Net GridView using Empty Data Template

Comments

Popular posts from this blog

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {     ...

Scrollable GridView with Fixed Headers using jQuery Plugin

Using the same example I have created a jQuery Plugin for Scrollable GridView with Fixed header so that you can directly make a GridView scrollable.   HTML Markup < form   id ="form1"   runat ="server"> < asp : GridView   ID ="GridView1"   runat ="server"   AutoGenerateColumns   =   "false"> < Columns > < asp : BoundField   DataField   =   "ContactName"   HeaderText   =   "Contact Name"   /> < asp : BoundField   DataField   =   "City"   HeaderText   =   "City"   /> < asp : BoundField   DataField   =   "Country"   HeaderText   =   "Country"   /> Columns > asp : GridView > form >   Applying the Scrollable Grid jQuery Plugin < script   src ="Scripts/jquery-1.4.1.min.js"   type ="text/javascript"> script > < script   src ="Scripts/Scro...