Tuesday, August 28

Adding And Removing Dynamic Rows in ASP.Net GridView Control


Here I am going to explain you how to add dynamic rows in a gridview control by click on Add button and simultaneously Remove dynamic rows from gridview Control by click on Remove button. I have used here one aspx page with a gridview control.Also I have used two images as Add.jpg and Remove.jpg in my images folder as shown Below:-

My GridView View As:-



My Database  Design is like Below:-

Now Here is my Table Defination:-
Reference_ID int        Unchecked
Title    varchar(10)    Checked
First_Name    varchar(15)    Checked
Middle_Name            varchar(15)    Checked
Last_Name     varchar(15)    Checked
Reference_Type        varchar(15)    Checked
Emp_Member_ID      int        Checked
Emp_Member_Type varchar(15)    Checked
Created_On   datetime         Checked
Created_By    int        Checked
Modified_On  datetime         Checked
Modified_By  int        Checked
Is_Active        bit        Checked
Is_Deleted      bit        Checked
My Table Defination Looks Like :-


Now  We have to provide connectionstrigs in web.config.
Here I am providing My connection strings :-

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="ShibashishConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ShibashishAddRemoveRowFromGrid.mdf;Integrated Security=True;User Instance=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>


Now come to the Design Part. where you have to take one Gridview From Your ToolBox and and use your required controls inside that gridview.Here I am using Two DropDownList and Three TextBox Controls and Two Image Button controls as Add and Remove .
It Looks Like:-
My Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShibashishAddRemoveRowFromGridView.aspx.cs"
    Inherits="ShibashishAddRemoveRowFromGridView" %>

<!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>Shibashish Mohanty</title>
</head>
<body>
    <h1>
        Om Namah Shivaya</h1>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridGuardians" runat="server" AutoGenerateColumns="False" BorderColor="#507CD1"
            BorderStyle="Solid" BorderWidth="1" CellPadding="4" Font-Names="Verdana" Font-Size="9pt"
            ForeColor="#333333" GridLines="None" OnRowCommand="GridGuardians_RowCommand"
            ShowHeader="false">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <table cellpadding="-1" cellspacing="-1" style="border: none;">
                            <tr>
                                <td>
                                    <asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="false" CommandName="Add"
                                        Height="8" ImageUrl="~/images/Add.jpg" ToolTip="Add New Row" Visible='<%# Eval("ShowAddButton") %>'
                                        Width="8" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:ImageButton ID="imgBtnRemove" runat="server" CausesValidation="false" CommandName="Remove"
                                        Height="8" ImageUrl="~/images/Remove.jpg" ToolTip="Delete Row" Visible='<%# Eval("ShowRemoveButton") %>'
                                        Width="8" />
                                </td>
                            </tr>
                        </table>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlSelectType" runat="server" Text='<%#Eval("Reference_Type") %>'>
                            <asp:ListItem>Select</asp:ListItem>
                            <asp:ListItem>Father</asp:ListItem>
                            <asp:ListItem>Son</asp:ListItem>
                            <asp:ListItem>Brother</asp:ListItem>
                            <asp:ListItem>Spouse</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:DropDownList ID="DdlGridTitle" runat="server" Text='<%#Eval("Title") %>'>
                            <asp:ListItem>Select</asp:ListItem>
                            <asp:ListItem>Mr</asp:ListItem>
                            <asp:ListItem>Mrs</asp:ListItem>
                            <asp:ListItem>Shree</asp:ListItem>
                            <asp:ListItem>Miss</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TxtGuardFirstName" runat="server" Text='<%#Eval("First_Name") %>'
                            Width="120"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TxtGuardMiddleName" runat="server" Text='<%#Eval("Middle_Name") %>'
                            Width="120"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TxtGuardLastName" runat="server" Text='<%#Eval("Last_Name") %>'
                            Width="120"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


Here is my Code Behind:-

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

public partial class ShibashishAddRemoveRowFromGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindData();
            if (GridGuardians.Rows.Count == 0)
            {
                SetDefaultRow();
            }

        }
    }
//GridView RowCommand Event For Adding and Removing Rows From Gridview

    protected void GridGuardians_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName == "Add")
        {
            GridViewRow gridRow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RowIndex = gridRow.RowIndex;
            DataTable dt = new DataTable();
            DataColumn ShowButton = new DataColumn("ShowAddButton", typeof(bool));
            DataColumn ShowRemoveButton = new DataColumn("ShowRemoveButton", typeof(bool));
            DataColumn dcSelectTypeID = new DataColumn("Reference_Type", typeof(string));
            DataColumn dcSelectTitle = new DataColumn("Title", typeof(string));
            DataColumn dcFirstname = new DataColumn("First_Name", typeof(string));
            DataColumn dcMiddlename = new DataColumn("Middle_Name", typeof(string));
            DataColumn dcLastname = new DataColumn("Last_Name", typeof(string));
            dt.Columns.Add(dcSelectTypeID);
            dt.Columns.Add(dcFirstname);
            dt.Columns.Add(dcMiddlename);
            dt.Columns.Add(dcLastname);
            dt.Columns.Add(ShowRemoveButton);
            dt.Columns.Add(ShowButton);
            dt.Columns.Add(dcSelectTitle);
            foreach (GridViewRow dr in GridGuardians.Rows)
            {
                DataRow dtrow = dt.NewRow();
                DropDownList ddlSelectType = (DropDownList)dr.FindControl("ddlSelectType");
                dtrow["Reference_Type"] = ddlSelectType.SelectedItem.Text;

                DropDownList ddlSelectTitle = (DropDownList)dr.FindControl("DdlGridTitle");
                dtrow["Title"] = ddlSelectTitle.SelectedItem.Text;

                TextBox txtFirstname = (TextBox)dr.FindControl("TxtGuardFirstName");
                dtrow["First_Name"] = txtFirstname.Text;
                TextBox txtMiddleName = (TextBox)dr.FindControl("TxtGuardMiddleName");
                dtrow["Middle_Name"] = txtMiddleName.Text;
                TextBox txtLastname = (TextBox)dr.FindControl("TxtGuardLastName");
                dtrow["Last_Name"] = txtLastname.Text;
                ImageButton showbutton = (ImageButton)dr.FindControl("imgBtnAdd");
                dtrow["ShowAddButton"] = false;
                ImageButton showRemovebutton = (ImageButton)dr.FindControl("imgBtnRemove");
                dtrow["ShowRemoveButton"] = false;
                dt.Rows.Add(dtrow);

            }

            DataRow newRow = dt.NewRow();
            newRow["Reference_Type"] = "Select";
            newRow["Title"] = "Select";
            newRow["First_Name"] = "";
            newRow["Middle_Name"] = "";
            newRow["Last_Name"] = "";
            newRow["ShowAddButton"] = true;
            newRow["ShowRemoveButton"] = true;
            dt.Rows.Add(newRow);
            GridGuardians.DataSource = dt;
            GridGuardians.DataBind();

        }

        else if (e.CommandName == "Remove")
        {
            GridViewRow gridRow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RowIndex = gridRow.RowIndex;
            DataTable dt1 = new DataTable();
            DataColumn ShowButton = new DataColumn("ShowAddButton", typeof(bool));
            DataColumn ShowRemoveButton = new DataColumn("ShowRemoveButton", typeof(bool));
            DataColumn dcSelectTypeID = new DataColumn("Reference_Type", typeof(string));
            DataColumn dcSelectTitle = new DataColumn("Title", typeof(string));
            DataColumn dcFirstname = new DataColumn("First_Name", typeof(string));
            DataColumn dcMiddlename = new DataColumn("Middle_Name", typeof(string));
            DataColumn dcLastname = new DataColumn("Last_Name", typeof(string));
            dt1.Columns.Add(dcSelectTypeID);
            dt1.Columns.Add(dcFirstname);
            dt1.Columns.Add(dcMiddlename);
            dt1.Columns.Add(dcLastname);
            dt1.Columns.Add(ShowRemoveButton);
            dt1.Columns.Add(ShowButton);
            dt1.Columns.Add(dcSelectTitle);
            foreach (GridViewRow dr in GridGuardians.Rows)
            {
                DataRow dtrow = dt1.NewRow();
                DropDownList ddlSelectType = (DropDownList)dr.FindControl("ddlSelectType");
                dtrow["Reference_Type"] = ddlSelectType.SelectedItem.Text;
                DropDownList ddlSelectTitle = (DropDownList)dr.FindControl("DdlGridTitle");
                dtrow["Title"] = ddlSelectTitle.SelectedItem.Text;
                TextBox txtFirstname = (TextBox)dr.FindControl("TxtGuardFirstName");
                dtrow["First_Name"] = txtFirstname.Text;
                TextBox txtMiddleName = (TextBox)dr.FindControl("TxtGuardMiddleName");
                dtrow["Middle_Name"] = txtMiddleName.Text;
                TextBox txtLastname = (TextBox)dr.FindControl("TxtGuardLastName");
                dtrow["Last_Name"] = txtLastname.Text;
                ImageButton showbutton = (ImageButton)dr.FindControl("imgBtnAdd");
                dtrow["ShowAddButton"] = false;
                ImageButton showRemovebutton = (ImageButton)dr.FindControl("imgBtnRemove");
                dtrow["ShowRemoveButton"] = false;
                dt1.Rows.Add(dtrow);
            }
            dt1.Rows.RemoveAt(RowIndex);
            GridGuardians.DataSource = dt1;
            GridGuardians.DataBind();
            if (GridGuardians.Rows.Count > 0)
            {
                ImageButton imgLast = (ImageButton)GridGuardians.Rows[GridGuardians.Rows.Count - 1].FindControl("imgBtnRemove");
                imgLast.Visible = true;
                ImageButton imgFirst = (ImageButton)GridGuardians.Rows[GridGuardians.Rows.Count - 1].FindControl("imgBtnAdd");
                imgFirst.Visible = true;
            }

        }
    }
//Methods For Binding Data to Gridview

    #region BindGurdians GridView

    private void BindData()
    {
        string strConnString = ConfigurationManager.ConnectionStrings["ShibashishConnectionString"].ConnectionString;
        DataTable dtSelect = new DataTable();
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            string strQuery = "SELECT [Reference_ID], [Title], [First_Name], [Middle_Name], [Last_Name], [Reference_Type], [Emp_Member_Type] FROM [Shibashish'sGuardians]";
            SqlCommand cmd = new SqlCommand(strQuery);
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dtSelect);
                DataTable dt = new DataTable();
                DataColumn ShowButton = new DataColumn("ShowAddButton", typeof(bool));
                DataColumn ShowRemoveButton = new DataColumn("ShowRemoveButton", typeof(bool));
                DataColumn dcSelectTypeID = new DataColumn("Reference_Type", typeof(string));
                DataColumn dcSelectTitle = new DataColumn("Title", typeof(string));
                DataColumn dcFirstname = new DataColumn("First_Name", typeof(string));
                DataColumn dcMiddlename = new DataColumn("Middle_Name", typeof(string));
                DataColumn dcLastname = new DataColumn("Last_Name", typeof(string));
                dt.Columns.Add(dcSelectTypeID);
                dt.Columns.Add(dcFirstname);
                dt.Columns.Add(dcMiddlename);
                dt.Columns.Add(dcLastname);
                dt.Columns.Add(ShowRemoveButton);
                dt.Columns.Add(ShowButton);
                dt.Columns.Add(dcSelectTitle);
                foreach (DataRow dr in dtSelect.Rows)
                {
                    DataRow newRow = dt.NewRow();
                    newRow["Reference_Type"] = dr["Reference_Type"].ToString();
                    newRow["Title"] = dr["Title"].ToString();
                    newRow["First_Name"] = dr["First_Name"].ToString();
                    newRow["Middle_Name"] = dr["Middle_Name"].ToString();
                    newRow["Last_Name"] = dr["Last_Name"].ToString();
                    newRow["ShowAddButton"] = true;
                    newRow["ShowRemoveButton"] = true;
                    dt.Rows.Add(newRow);
                }
                GridGuardians.DataSource = dt;
                GridGuardians.DataBind();
            }
        }
    }
    #endregion
//Show Default Row if there is no data inside the Gridview

    #region Default Row Method
    public void SetDefaultRow()
    {
        DataTable dt = new DataTable();
        DataColumn ShowButton = new DataColumn("ShowAddButton", typeof(bool));
        DataColumn ShowRemoveButton = new DataColumn("ShowRemoveButton", typeof(bool));
        DataColumn dcSelectTypeID = new DataColumn("Reference_Type", typeof(string));
        DataColumn dcSelectTitle = new DataColumn("Title", typeof(string));
        DataColumn dcFirstname = new DataColumn("First_Name", typeof(string));
        DataColumn dcMiddlename = new DataColumn("Middle_Name", typeof(string));
        DataColumn dcLastname = new DataColumn("Last_Name", typeof(string));
        dt.Columns.Add(dcSelectTypeID);
        dt.Columns.Add(dcFirstname);
        dt.Columns.Add(dcMiddlename);
        dt.Columns.Add(dcLastname);
        dt.Columns.Add(ShowRemoveButton);
        dt.Columns.Add(ShowButton);
        dt.Columns.Add(dcSelectTitle);
        DataRow newRow = dt.NewRow();
        newRow["Reference_Type"] = "Select";

        newRow["Title"] = "Select";
        newRow["First_Name"] = "";
        newRow["Middle_Name"] = "";
        newRow["Last_Name"] = "";
        newRow["ShowAddButton"] = true;
        newRow["ShowRemoveButton"] = true;
        dt.Rows.Add(newRow);
        GridGuardians.DataSource = dt;
        GridGuardians.DataBind();
    }

    #endregion
}

Now After running it Will Display As:-


Here I am Clicking Plus Button By which it will add a new Row and it looks like Below Figure:-



Now Again I am Clicking on Plus Button It will add Another Row as Shown Below:-



Now By Click on Remove Button It will Remove One Row As Below:-




Thanks Shibashish Mohanty


6 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. hiii shibashish your article is superb i was seraching for this since last week and i have req on this i.e i want to insert data by using gridview through into database multiple tables is it possible if yes how please gimme a suggestion to dis..

    ReplyDelete
    Replies
    1. Please go for this link

      http://shibashishdotnetocean.blogspot.in/2012/02/save-dynamic-textbox-values-from.html

      here I'm sending data to single table similarly you can post data to multiple table by writing sql query for inserting respective tables.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. hiii shibashish your article is superb i was seraching for this since last week and i have req on this i.e i want to insert data by using gridview into database through multiple tables if thr are 5 columns in the gridview those 5 columns belongs to 5 different tables in th database is it possible if yes how please gimme a suggestion to dis..

    ReplyDelete
    Replies
    1. sure at the time of save button click event, you just write 5 insert statement according to your table.

      Delete

Please don't spam, spam comments is not allowed here.

ShibashishMnty
shibashish mohanty