ADD TextBox to GridView FooterRow and Display Auto Generate ID and also Bind TextBox Data to Gridview

ADD TextBox to GridView FooterRow and Display Auto Generate ID and also Bind TextBox Data to Gridview

Have you ever wondered how to enhance your ASP.NET web application by allowing users to input data directly into the GridView control's FooterRow? In this article, we'll explore the process of integrating two TextBox controls and a Button control into the GridView FooterRow. Our goal is to add country names, where one TextBox displays an automatically generated country ID (e.g., cnt1, cnt2, cnt3), and the other TextBox accepts the country name. Upon clicking the Add Button, the data entered in the TextBoxes will be stored in the database and retrieved to update the GridView control.

Create DataBase Table: Country

Before we start, let's create a database table named 'Country' with columns 'ID,' 'countryid,' and 'countryname.'


CREATE TABLE [dbo].[Country](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [countryid] [nvarchar](50) NOT NULL,
 [countryname] [nvarchar](50) NULL
) ON [PRIMARY]

GO

Add GridView Control: HTML Page

In our ASP.NET application, we set up a GridView control with two TemplateFields for displaying Country ID and Country Name. Additionally, we include TextBox controls and a Button in the FooterTemplate for user input. The GridView is designed to display data fetched from the 'Country' table.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewWithFooter.aspx.cs" Inherits="GridviewWithFooter" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" 
            CellPadding="4" ShowFooter="True">
            <Columns>
                <asp:TemplateField HeaderText="Country ID">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bindundefined"countryid") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txt_addcountryid" BackColor="#dddddd" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_countryid" runat="server" Text='<%# Bindundefined"countryid") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bindundefined"countryname") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txt_addcountryname" runat="server"></asp:TextBox>
                        <asp:Button ID="btn_country" runat="server" onclick="btn_country_Click" 
                            Text="Add" />
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bindundefined"countryname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#003399" ForeColor="#003399" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <RowStyle BackColor="White" ForeColor="#003399" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <SortedAscendingCellStyle BackColor="#EDF6F6" />
            <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
            <SortedDescendingCellStyle BackColor="#D6DFDF" />
            <SortedDescendingHeaderStyle BackColor="#002876" />
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

C# Coding: C# Coding: Namespace and Page Load Event

In our C# code-behind, we begin by including necessary namespaces and establishing a SqlConnection. In the Page_Load event, we check if the page is not a postback, and if not, we call the FillGridviewData method.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class GridviewWithFooter : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbCon"].ToString());
    string query;
    string countid = "cnt";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillGridviewData();
        }
    }
}

C# Coding: Bind Gridview

The FillGridviewData method is responsible for binding data to the GridView. If the 'Country' table is empty, we dynamically add a row to display a "No Records Found" message. We also generate an auto-incremented country ID for user convenience.


    private void FillGridviewData()
    {
        query = "select * from Country";
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "country");
        if (ds.Tables[0].Rows.Count == 0)
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            int columncount = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
            GridView1.Rows[0].Cells[0].Text = "No Records Found";

            query = "select countryid=Count(countryid) from Country";
            con.Open();
            SqlCommand cmd = new SqlCommand(query, con);
            string cid = cmd.ExecuteScalar().ToString();
            con.Close();
            GridViewRow row = GridView1.FooterRow;
            TextBox txtcountrid = (TextBox)row.FindControl("txt_addcountryid");
            txtcountrid.Text = countid + (int.Parse(cid) + 1);
            txtcountrid.ReadOnly = true;
        }
        else
        {
            GenerateAutoCountryID();
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
    
}

C# Coding: Generate Auto Country ID

To automatically generate the country ID, we use the GenerateAutoCountryID method. This method queries the database to obtain the count of existing country IDs and increments it to generate the next ID.


private void GenerateAutoCountryID()
    {
        try
        {
            query = "select countryid=Count(countryid) from Country";
            con.Open();
            SqlCommand cmd = new SqlCommand(query, con);
            string cid = cmd.ExecuteScalar().ToString();
            con.Close();
            GridViewRow row = GridView1.FooterRow;
            TextBox txtcountrid = (TextBox)row.FindControl("txt_addcountryid");
            txtcountrid.Text = countid + (int.Parse(cid) + 1);
            txtcountrid.ReadOnly = true;
        }
        catch
        {
            throw;
        }
    }

C# Coding: Add Button Click Event

The btn_country_Click method handles the click event of the Add Button. It retrieves the user-entered country ID and name from the TextBoxes, inserts the data into the 'Country' table, and refreshes the GridView.


protected void btn_country_Click(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.FooterRow;
        TextBox txtcountrid = (TextBox)row.FindControl("txt_addcountryid");
        TextBox txtcountrname = (TextBox)row.FindControl("txt_addcountryname");
        string countryid = txtcountrid.Text;
        string countryname = txtcountrname.Text;
        //Database query

        query = "Insert into Country values('" + countryid + "','" + countryname + "')";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        con.Close();
        FillGridviewData();
        GenerateAutoCountryID();
    }

Download Project with Source Code

If you'd like to explore the complete project with source code, you can download from here.

Now you have a powerful GridView implementation that allows users to seamlessly add data using TextBox controls in the FooterRow. Implement this feature in your ASP.NET applications to enhance data input and management capabilities.

Post a Comment

0 Comments