Friday, 3 October 2014

How to Add Dynamic Rows in Gridview in ASP.NET

In this article, i am going to show how to add dynamic rows in gridview control..

aspx page

 <asp:GridView ID="gvRecords" runat="server" OnRowCommand="gvRecords_RowCommand" DataKeyNames="SrNo" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Sr No.">
                <ItemTemplate>
                    <asp:TextBox ID="txtSrNo" runat="server" Text='<%# Eval("SrNo") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Name">
                <ItemTemplate>
                    <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Salary">
                <ItemTemplate>
                    <asp:TextBox ID="txtAmount" runat="server" Text='<%# Eval("Salary") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:ButtonField ButtonType="Button" CommandName="cmd_delete" Text="Delete" />
        </Columns>
    </asp:GridView>
    <asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />

cs page

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

public partial class dynamicgridview : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvRecords.DataSource = GetTableWithInitialData(); // get initial data
            gvRecords.DataBind();
        }
    }

    public DataTable GetTableWithInitialData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("SrNo", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Salary", typeof(double));

        table.Rows.Add(1, "Manpreet", 25000);
        table.Rows.Add(2, "Gurpreet", 20000);
        table.Rows.Add(3, "Prabhjot", 33000);
        SaveGridInViewstate(table);
        return table;
    }

    protected void btnAddRow_Click(object sender, EventArgs e)
    {
        DataTable dt = GetTableWithNoData(); // get table structure by calling the specified function
        DataRow dr;

        foreach (GridViewRow gvr in gvRecords.Rows)
        {
            dr = dt.NewRow();

            TextBox txtSrNo = gvr.FindControl("txtSrNo") as TextBox;
            TextBox txtName = gvr.FindControl("txtName") as TextBox;
            TextBox txtAmount = gvr.FindControl("txtAmount") as TextBox;
            dr[0] = txtSrNo.Text;
            dr[1] = txtName.Text;

            if (txtAmount.Text == string.Empty)
            {
                dr[2] = DBNull.Value;
            }

            else
            {
                dr[2] = txtAmount.Text;
            }

            dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
        }

        dr = dt.NewRow(); // add new empty row
        dt.Rows.Add(dr);

        gvRecords.DataSource = dt; // bind newly created datatable to grid
        gvRecords.DataBind();
        SaveGridInViewstate(dt);
    }

    public DataTable GetTableWithNoData() // returns only table structure 
    {
        DataTable table = new DataTable();
        table.Columns.Add("SrNo", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Salary", typeof(double));
        return table;
    }

    // save datatable into viewstate which would be useful for deletion
    public void SaveGridInViewstate(DataTable dt)
    {
        ViewState["gvRecords"] = dt;
    }

    protected void gvRecords_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmd_delete")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            if (ViewState["gvRecords"] != null)
            {
                dt = ViewState["gvRecords"] as DataTable;
                DataRow row = dt.Rows[index];
                dt.Rows.Remove(row);
                gvRecords.DataSource = dt; // bind newly created datatable to grid
                gvRecords.DataBind();
            }
        }
    }
}
Output

That’s it!!…..Happy Programming...

No comments:

Post a Comment