How To Insert A New Row In GridView-ASP.NET

In this article, I will show you how to insert a record in ASP.NET GridView Control with a complete example


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InsertRowInGridView.aspx.cs"
   Inherits="InsertRowGridView" %>

<!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 id="Head1" runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView AutoGenerateColumns="False" ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
               OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand">
               <Columns>
                   <asp:TemplateField ShowHeader="False">
                       <EditItemTemplate>
                           <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                               Text="Update"></asp:LinkButton>
                           <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                               Text="Cancel"></asp:LinkButton>
                       </EditItemTemplate>
                       <FooterTemplate>
                           <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Insert">Insert</asp:LinkButton>
                       </FooterTemplate>
                       <ItemTemplate>
                           <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                               Text="Edit"></asp:LinkButton>
                       </ItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField>
                       <FooterTemplate>
                           <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                       </FooterTemplate>
                       <ItemTemplate>
                           <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
                       </ItemTemplate>
                       <EditItemTemplate>
                           <asp:TextBox ID="txtID" runat="server" Text='<%#Bind("ID") %>'></asp:TextBox>
                       </EditItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField HeaderText="Name">
                       <FooterTemplate>
                           <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                       </FooterTemplate>
                       <ItemTemplate>
                           <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                       </ItemTemplate>
                       <EditItemTemplate>
                           <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>'></asp:TextBox>
                       </EditItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
       </div>
       <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" />
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class InsertRowGridView : System.Web.UI.Page
{
   DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            BindGrid();

        }

    }

    private void BindGrid()
    {

        DataTable dt = new DataTable(); dt = (DataTable)Session["MyDataSource"];


        GridView1.DataSource = GetDataSource();

        GridView1.DataBind();

    }

    protected DataTable GetDataSource()
    {

        const string key = "MyDataSource";
        DataTable dt = Session[key] as DataTable;

        if (dt == null)
        {

            dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));

            dt.Columns.Add("Name", typeof(string));
            dt.Rows.Add("1", "first object");

            dt.Rows.Add("2", "second object");
            Session[key] = dt;

        }

        return dt;
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

        GridView1.EditIndex = e.NewEditIndex;

        BindGrid();

    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

        GridView1.EditIndex = -1;

        BindGrid();

    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        GridViewRow row = GridView1.Rows[e.RowIndex];
        GridView1.EditIndex = -1;

        if (row != null)
        {

            TextBox txtID = GridView1.Rows[e.RowIndex].Cells[0].FindControl("txtID") as TextBox;
            TextBox txtName = GridView1.Rows[e.RowIndex].Cells[1].FindControl("txtName") as TextBox;

            dt = (DataTable)Session["MyDataSource"];



            for (int i = 0; i < dt.Rows.Count; i++)
            {

                if (e.RowIndex == i)
                {

                    dt.Rows[i][1] = txtName.Text;

                    dt.Rows[i][0] = Convert.ToInt32(txtID.Text);


                    Session["MyDataSource"] = dt;

                    GridView1.DataSource = dt;
                    GridView1.DataBind();

                }

            }

        }

    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Insert")
        {
            // these are alternate ways of getting to grid
            //GridView gv = sender as GridView;
            //GridView gv = (GridView)sender;
            AddData();

            GridView1.ShowFooter = false;
            BindGrid();
           
            btnAdd.Enabled = true;
        }
    }

    protected void AddData()
    {
        DataTable  dt = (DataTable)Session["MyDataSource"];
        DataRow rw = dt.NewRow();
        TextBox txt = (TextBox)GridView1.FooterRow.Cells[1].FindControl("TextBox1");
        rw[0] = Convert.ToInt32(txt.Text);
        txt = (TextBox)GridView1.FooterRow.Cells[2].FindControl("TextBox2");
        rw[1] = txt.Text;
        dt.Rows.Add(rw);
        Session["MyDataSource"] = dt;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        GridView1.ShowFooter = true;
        BindGrid();

        btnAdd.Enabled = false;
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru