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

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        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to solve this browser compatibility proble

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour