Click here to Skip to main content
12,827,807 members (46,941 online)
Click here to Skip to main content
Add your own
alternative version


207 bookmarked
Posted 6 Feb 2008

Editable GridView in ASP.NET 2.0

, 26 Nov 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
This article will give you an overview of how to use an ASP.NET GridView completely, and how to use RowEditing, RowUpdating, RowDeleting, RowCommand, RowDataBound, RowCancelingEdit, and Pagination in a DataGrid. From this article, you will have a clear view of GridView data inserting, deleting, and



This article will give you an overview of how to use an asp:GridView completely, and how to use RowEditing, RowUpdating, RowDeleting, RowCommand, RowDataBound, RowCancelingEdit, and Pagination in a DataGrid. From this article, you will have a clear view of the GridView data insert, delete, and update operations.


GridView is a very popular control in ASP.NET, and for website development, it is a very important control. This control is especially important for CRUD operations.

Using the code

Make two tables in a database: Contact and ContactType. This is just an example of how we shall add, edit, and delete data in a GridView. I have also used a textbox, a drop down list, and a checkbox which we use in the case of data add, delete, and update.

Step by step

Take a web project, go to an .aspx page, for example, Default.aspx, and add an ASP.NET GridView:

<asp:GridView ID="grdContact" runat="server" 
 AutoGenerateColumns="False" DataKeyNames="Id, Type" 
 OnRowUpdating="grdContact_RowUpdating" ShowFooter="True" 

This is the GridView with all the necessary properties enabled and the events called.

For every column of the GridView, we need to make an <asp:TemplateField> field. I am using an <EditItemTemplate> to put the edit control, an <ItemTemplate> to bind data in a control, and a <FooterTemplate> to insert the control. Here is an example of a template field:

<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left"> 
    <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox> 
    <asp:TextBox ID="txtNewName" runat="server" ></asp:TextBox> 
    <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label> 


Let's take a look at the code for the GridView:

  1. Initialize the GridView: To fill data in the GridView, I have written a method named FillGrid() which takes data from a DataTable and shows it in the grid.
    public void FillGrid()
        ContactTableAdapter contact = new ContactTableAdapter();
        DataTable contacts = contact.GetData();
        if (contacts.Rows.Count > 0)
            grdContact.DataSource = contacts;
            grdContact.DataSource = contacts;
            int TotalColumns = grdContact.Rows[0].Cells.Count;
            grdContact.Rows[0].Cells.Add(new TableCell());
            grdContact.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            grdContact.Rows[0].Cells[0].Text = "No Record Found";
  2. Fill dynamic values: There are two dropdownlist controls available in this example. One of the dropdownlists dynamically loads data from another table. In the RowDataBound event of the GridView control, insert the following code:
    protected void grdContact_RowDataBound(object sender, GridViewRowEventArgs e)
        ContactTypeTableAdapter contactType = new ContactTypeTableAdapter();
        DataTable contactTypes = contactType.GetData();
        if (e.Row.RowType == DataControlRowType.DataRow)
            Label lblType = (Label)e.Row.FindControl("lblType");
            if (lblType != null)
                int typeId = Convert.ToInt32(lblType.Text);
                lblType.Text = (string)contactType.GetTypeById(typeId);
            DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");
            if (cmbType != null)
                cmbType.DataSource = contactTypes;
                cmbType.DataTextField = "TypeName";
                cmbType.DataValueField = "Id";
                cmbType.SelectedValue =
        if (e.Row.RowType == DataControlRowType.Footer)
            DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
            cmbNewType.DataSource = contactTypes;
  3. Insert data: I have initialized the GridView control with the DataTable, and also have some values filled in the footer dropdownlist, cmbNewType. Except Id, I have put FooterTemplate for every column because all the field are available. Clicking on "Insert" will enter data in your database table.
    protected void grdContact_RowCommand(object sender, GridViewCommandEventArgs e)
        ContactTableAdapter contact = new ContactTableAdapter();
        bool flag= false;
        if (e.CommandName.Equals("Insert"))
            TextBox txtNewName = 
            CheckBox chkNewActive = 
            DropDownList cmbNewType = 
            DropDownList ddlNewSex = 
            if (chkNewActive.Checked) flag = true; else flag = false;
            contact.Insert(txtNewName.Text, ddlNewSex.SelectedValue, 
                           cmbNewType.SelectedValue, flag);
  4. Update data: In the case of data update, we do the same things as the insert. In the case of insert, I always took the footer row, but in the case of update, I take the current RowIndex or the selected RowIndex. Click on Edit first, then call RowEditing, then the update and cancel options come.
    protected void grdContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
        ContactTableAdapter contact = new ContactTableAdapter();
        bool flag = false;
        Label lblId = (Label)grdContact.Rows[e.RowIndex].FindControl("lblId");
        TextBox txtName = (TextBox)grdContact.Rows[e.RowIndex].FindControl("txtName");
        CheckBox chkActive = 
        DropDownList cmbType = 
        DropDownList ddlSex = 
        if (chkActive.Checked) flag = true; else flag = false;
        contact.Update(txtName.Text, ddlSex.SelectedValue, 
                       cmbType.SelectedValue, flag,Convert.ToInt32(lblId.Text));
        grdContact.EditIndex = -1;
    protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)
        grdContact.EditIndex = e.NewEditIndex;
    protected void grdContact_RowCancelingEdit(object sender, 
                              GridViewCancelEditEventArgs e)
        grdContact.EditIndex = -1;
  5. Deleting data: Now, you may need to delete data. The GridView calls RowDeleting for the delete event.
    protected void grdContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
        ContactTableAdapter contact = new ContactTableAdapter();
        int id = Convert.ToInt32(grdContact.DataKeys[e.RowIndex].Values[0].ToString());

Points of Interest

So, now you have a DatGrid that is editable? Do you want to use CSS to give an excellent look of your grid? Just go to this link for a GridView CSS.

Happy coding


I was working on an admin panel in one of my projects, and saw that I needed many add, delete, and update operations for that panel. Now, I can easily solve that problem without a lot of programming by using an editable GridView.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ashrafur Rahaman
Software Developer (Senior)
Canada Canada
Software engineer with broad experience in enterprise application development, product deployment automation, software test & test automation, application & system management, and manage big projects and team using proven agile technologies.

Passionate on Microsoft technologies, developed solutions using C#, .net (1.1/2.0/3.5/4), SQL Server (2005/2008). Work on Powershell, SSRS, SSIS, WPF, Ajax, WCF, JQuery.

Develop innovative application with cutting edge technologies always boosting inside.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Menon Santosh27-Mar-13 21:31
memberMenon Santosh27-Mar-13 21:31 
Question.Problem accessing xsd Pin
Dimaz Janu19-Mar-13 17:44
memberDimaz Janu19-Mar-13 17:44 
QuestionShowing 5 Errors Pin
Girish_Sharma16-Mar-13 2:31
memberGirish_Sharma16-Mar-13 2:31 
QuestionHide Insert option Pin
Girish_Sharma14-Mar-13 20:42
memberGirish_Sharma14-Mar-13 20:42 
AnswerRe: Hide Insert option Pin
Ashrafur Rahaman15-Mar-13 6:13
memberAshrafur Rahaman15-Mar-13 6:13 
GeneralRe: Hide Insert option Pin
Girish_Sharma16-Mar-13 2:33
memberGirish_Sharma16-Mar-13 2:33 
QuestionDefinition of ContactTypeTableAdapter Pin
Vineesh Madhavan28-Feb-13 1:01
memberVineesh Madhavan28-Feb-13 1:01 
QuestionNeed advice Pin
Dimaz Janu26-Feb-13 18:22
memberDimaz Janu26-Feb-13 18:22 

I've made some change on your code.
I have put button on FooterRow that will pop up window and then send some return value.
I have manage send these return value to web form (outside gridview).
My question is how can I send these return value to your editable gridview (let's say to textbox on footer row) ?

here my code
On my parent code behind:

protected void grdContact_RowCommand(object sender, GridViewCommandEventArgs e)
SalesLineTableAdapter xNUP = new SalesLineTableAdapter();
int flag = 0;
//bool flag= false;
if (e.CommandName.Equals("Insert"))
DropDownList ddlNewKodeItem = (DropDownList)grdContact.FooterRow.FindControl("ddlNewItemCode");
TextBox txtNewJml = (TextBox)grdContact.FooterRow.FindControl("txtNewJml");
TextBox txtNewHarg = (TextBox)grdContact.FooterRow.FindControl("txtNewHarga");
//DropDownList ddlNewKodeGrade = (DropDownList)grdContact.FooterRow.FindControl("ddlNewKodeGrade");
CheckBox chkNewActive = (CheckBox)grdContact.FooterRow.FindControl("chkNewActive");
if (chkNewActive.Checked) flag = 1; else flag = 0;
xNUP.InsertSales(DocSO, DocInv, DateTime.Now, "", ddlNewKodeItem.SelectedValue, "", Convert.ToDecimal(txtNewJml.Text.ToString()), Convert.ToDecimal(txtNewHarg.Text.ToString()), 0, 0, 0);
updateInvent(cboKodePaket.SelectedValue, ddlNewKodeItem.SelectedValue, Convert.ToDecimal(txtNewJml.Text.ToString()));
if (e.CommandName.Equals("Cari"))
TextBox txtItem = (TextBox)grdContact.FooterRow.FindControl("txtNewItem");
Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "AddScript", "openItem('" + txtItem.Text + "')", true);

On My parent script:

function upItem(value1,value2,value3,value4)
document.form1.txtValue1.value = value1;
document.form1.txtValue2.value = value2;
document.form1.txtValue3.value = value3;
document.form1.txtValue4.value = value4;

function openItem(text)
var retIval=' ';

retIval ='PopItem.aspx?ItemName=' + text ,'','status,height=500,width=800');



On My Child Script:


function SetData(ItemCode, ItemName, Satuan, HargaJual)

document.form1.txtTest.value = ItemCode;
return false;


AnswerRe: Need advice Pin
Ashrafur Rahaman3-Mar-13 5:14
memberAshrafur Rahaman3-Mar-13 5:14 
GeneralRe: Need advice Pin
Dimaz Janu4-Mar-13 14:46
memberDimaz Janu4-Mar-13 14:46 
GeneralMy vote of 5 Pin
Dimaz Janu26-Feb-13 18:08
memberDimaz Janu26-Feb-13 18:08 
QuestionThank you Ashrafur - this was very helpful Pin
Ginger Decker25-Feb-13 11:26
memberGinger Decker25-Feb-13 11:26 
GeneralMy vote of 5 Pin
Varun Sareen10-Dec-12 19:30
memberVarun Sareen10-Dec-12 19:30 
GeneralMy vote of 3 Pin
Md. Humayun Rashed26-Nov-12 5:42
memberMd. Humayun Rashed26-Nov-12 5:42 
Questionnice:) Pin
Ashwin78626-Sep-12 22:44
memberAshwin78626-Sep-12 22:44 
GeneralMy vote of 5 Pin
saikiranmai4-Sep-12 22:29
membersaikiranmai4-Sep-12 22:29 
QuestionEdit update Delete in Gridview Pin
jigs080817-Aug-12 6:29
memberjigs080817-Aug-12 6:29 
QuestionGood Pin
padma777.vathi29-Jul-12 22:15
memberpadma777.vathi29-Jul-12 22:15 
GeneralMy vote of 3 Pin
padma777.vathi29-Jul-12 22:12
memberpadma777.vathi29-Jul-12 22:12 
GeneralLimited select query and XSD file Pin
maxgo17-Jul-12 11:52
membermaxgo17-Jul-12 11:52 
GeneralTwo footers? Pin
shawnperolis12-Jul-12 5:50
membershawnperolis12-Jul-12 5:50 
GeneralRe: Two footers? Pin
shawnperolis17-Jul-12 5:18
membershawnperolis17-Jul-12 5:18 
GeneralMy vote of 4 Pin
dippaul31-May-12 1:04
memberdippaul31-May-12 1:04 
GeneralMy vote of 1 Pin
Destiny7777-May-12 16:16
memberDestiny7777-May-12 16:16 
GeneralMy vote of 5 Pin
LSADev2-May-12 10:37
memberLSADev2-May-12 10:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170326.1 | Last Updated 26 Nov 2012
Article Copyright 2008 by Ashrafur Rahaman
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid