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

Hierarchical GridView in ASP.NET with AJAX, JQuery implementation - Part 1

Previously I had blogged some post related to showing two grids in hierarchical way. For example - when I need to show an invoice reports on the screen, the user requesting to show the list of invoices at initial time and they can drill down the details of item details of each invoice by clicking on respective row. The implementations can be in multiple ways, but I had blogged the implementation with AJAX and without AJAX using Java script on ASP.NET page. Below are the URLs of the same – Hierarchical GridView in ASP.NET Hierarchical GridView in ASP.NET with AJAX, Javascript implementation In this post I am taking the same requirements done before and enhance with some additional functionality as per readers expectations. The requirement on this implementation will be – The page should show a Grid View with list of Orders with Expand icon on the first column. On click of expand icon on each row, the Order Details of the Order must be fetched from the database ...

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        {     ...

JQuery lightbox image slideshow gallery in asp.net

Introduction: In this article I will explain how to create lightbox image slideshow in asp.net using JQuery. Description:  In previous post I explained about  Ajax SlideshowExtender sample  to display images slideshow. Now in this article I will explain how to create lightbox image slideshow in asp.net using JQuery. In many websites generally we will see different types of slideshows like whenever we click on image that is automatically open with lightbox effect and we have a chance to see all the remaining images by press next or previous options in slideshow. All these Slideshows are implemented by using JQuery plugins. After seen those slideshows I decided to write post to use JQuery plugins to implement beautiful slideshown in asp.net.  To implement this one I am using  previous post  insert and display images from folder based on imagepath in database  because in that post I explained clearly how to insert images into our project folder a...