Click here to Skip to main content
11,716,133 members (86,952 online)
Click here to Skip to main content

Editable GridView in ASP.NET 2.0

, 26 Nov 2012 CPOL 773.2K 45.4K 202
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

EditableGridView

Introduction

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.

Background

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" 
 OnRowCancelingEdit="grdContact_RowCancelingEdit" 
 OnRowDataBound="grdContact_RowDataBound" 
 OnRowEditing="grdContact_RowEditing" 
 OnRowUpdating="grdContact_RowUpdating" ShowFooter="True" 
 OnRowCommand="grdContact_RowCommand" 
 OnRowDeleting="grdContact_RowDeleting">

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"> 
   <EditItemTemplate> 
    <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox> 
   </EditItemTemplate> 
   <FooterTemplate> 
    <asp:TextBox ID="txtNewName" runat="server" ></asp:TextBox> 
   </FooterTemplate> 
   <ItemTemplate> 
    <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label> 
   </ItemTemplate>
</asp:TemplateField>

Editable_GridView/Editable_GridView2.png

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.DataBind();
        }
        else
        {
            contacts.Rows.Add(contacts.NewRow());
            grdContact.DataSource = contacts;
            grdContact.DataBind();
    
            int TotalColumns = grdContact.Rows[0].Cells.Count;
            grdContact.Rows[0].Cells.Clear();
            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.DataBind();
                cmbType.SelectedValue =
                  grdContact.DataKeys[e.Row.RowIndex].Values[1].ToString();
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
            cmbNewType.DataSource = contactTypes;
            cmbNewType.DataBind();
        }
    }
    
  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 = 
              (TextBox)grdContact.FooterRow.FindControl("txtNewName");
            CheckBox chkNewActive = 
              (CheckBox)grdContact.FooterRow.FindControl("chkNewActive");
            DropDownList cmbNewType = 
              (DropDownList)grdContact.FooterRow.FindControl("cmbNewType");
            DropDownList ddlNewSex = 
              (DropDownList)grdContact.FooterRow.FindControl("ddlNewSex");
            if (chkNewActive.Checked) flag = true; else flag = false;
            contact.Insert(txtNewName.Text, ddlNewSex.SelectedValue, 
                           cmbNewType.SelectedValue, flag);
            FillGrid();
        }
    }
  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 = 
          (CheckBox)grdContact.Rows[e.RowIndex].FindControl("chkActive");
        DropDownList cmbType = 
          (DropDownList)grdContact.Rows[e.RowIndex].FindControl("cmbType");
        DropDownList ddlSex = 
          (DropDownList)grdContact.Rows[e.RowIndex].FindControl("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;
        FillGrid();
        
    }
    protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdContact.EditIndex = e.NewEditIndex;
        FillGrid();
    }
    protected void grdContact_RowCancelingEdit(object sender, 
                              GridViewCancelEditEventArgs e)
    {
        grdContact.EditIndex = -1;
        FillGrid();
    }
  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());
        contact.Delete(id);
        FillGrid();
    }

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 Smile | :)

History

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. Smile | :)

License

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

Share

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 2 Pin
Alexander M. Batishchev22-Dec-11 9:59
memberAlexander M. Batishchev22-Dec-11 9:59 
GeneralRe: My vote of 2 Pin
Shemeer NS4-Jul-12 3:43
memberShemeer NS4-Jul-12 3:43 
QuestionGood Work Pin
Sachin Dubey13-Sep-11 22:53
memberSachin Dubey13-Sep-11 22:53 
GeneralMy vote of 4 Pin
Uday Kumar B R11-Aug-11 1:01
memberUday Kumar B R11-Aug-11 1:01 
QuestionHi Pin
ariel_alava7-Jul-11 23:13
memberariel_alava7-Jul-11 23:13 
GeneralMy vote of 5 Pin
Member 327776020-May-11 4:03
memberMember 327776020-May-11 4:03 
GeneralMy vote of 1 Pin
vikas dumbre11-May-11 3:18
membervikas dumbre11-May-11 3:18 
GeneralInvalid Object name 'Contact' Pin
RayH10664-May-11 22:33
memberRayH10664-May-11 22:33 
GeneralAbout ContactTableAdapter Pin
manjeet_2426-Apr-11 0:04
membermanjeet_2426-Apr-11 0:04 
GeneralRe: About ContactTableAdapter Pin
Member 80688958-Jul-11 2:49
memberMember 80688958-Jul-11 2:49 
GeneralRe: About ContactTableAdapter Pin
mohamedamine00728-Jan-12 4:40
membermohamedamine00728-Jan-12 4:40 
GeneralRe: About ContactTableAdapter Pin
Member 864050216-Feb-12 18:13
memberMember 864050216-Feb-12 18:13 
Generalneed ur urgent help Pin
sagar r.14-Apr-11 13:40
membersagar r.14-Apr-11 13:40 
GeneralMy vote of 4 Pin
jacky4lad16-Mar-11 19:20
memberjacky4lad16-Mar-11 19:20 
GeneralMy vote of 4 Pin
Vjayraj8-Mar-11 19:04
memberVjayraj8-Mar-11 19:04 
Questionproblem in grid Pin
patelpriyanka213-Mar-11 23:21
memberpatelpriyanka213-Mar-11 23:21 
AnswerRe: problem in grid Pin
n3rd702z9-Mar-11 9:35
membern3rd702z9-Mar-11 9:35 
GeneralHai Friends!!!! just try this link for gridview insert,update and delete without writing a single piece of code Pin
vijay_vignesh11-Jan-11 3:03
membervijay_vignesh11-Jan-11 3:03 
GeneralMy vote of 3 Pin
hemantbhadesia23-Nov-10 19:37
memberhemantbhadesia23-Nov-10 19:37 
GeneralGreat job! Pin
Kyryll99930-Aug-10 13:54
memberKyryll99930-Aug-10 13:54 
GeneralMy vote of 4 Pin
d_uvarajan22-Jul-10 3:56
memberd_uvarajan22-Jul-10 3:56 
Generalusing TestDatabaseTableAdapters Pin
Yuppski11-May-10 2:12
memberYuppski11-May-10 2:12 
GeneralExcellent Pin
Terceros22-Apr-10 17:40
memberTerceros22-Apr-10 17:40 
GeneralToo complex Pin
Kedar Vijay Kulkarni3-Jan-10 23:02
memberKedar Vijay Kulkarni3-Jan-10 23:02 
GeneralMy vote of 1 Pin
Naveen.255920-Dec-09 23:30
memberNaveen.255920-Dec-09 23:30 
GeneralMy vote of 1 Pin
AJFK30-Sep-09 9:26
memberAJFK30-Sep-09 9:26 
QuestionHow To Edit Grid View In Asp.net Using VB.... Pin
Ravindra VL22-Sep-09 2:55
memberRavindra VL22-Sep-09 2:55 
QuestionHow to hide the footer row when editing... Pin
danteprax15-Jul-09 9:01
memberdanteprax15-Jul-09 9:01 
GeneralDB Script. Pin
javed_alam78630-Jun-09 0:01
memberjaved_alam78630-Jun-09 0:01 
GeneralRe: DB Script. Pin
Sam Davis23-Oct-09 10:14
memberSam Davis23-Oct-09 10:14 
GeneralRe: DB Script. Pin
n3rd702z9-Mar-11 9:36
membern3rd702z9-Mar-11 9:36 
QuestionWhere is the database boss? Pin
Jags12121-May-09 1:40
memberJags12121-May-09 1:40 
AnswerRe: Where is the database boss? Pin
jahirhstu16-May-09 15:42
memberjahirhstu16-May-09 15:42 
AnswerRe: Where is the database boss? Pin
khongwir15-Sep-10 21:42
memberkhongwir15-Sep-10 21:42 
GeneralTable Design of Contact and ContactType Pin
chemlms9-Jan-09 7:44
memberchemlms9-Jan-09 7:44 
Generaladding validation Pin
mgetting3-Dec-08 19:11
membermgetting3-Dec-08 19:11 
Generalproblem with imagebutton instead of linkbutton Pin
Xildur12-Oct-08 8:22
memberXildur12-Oct-08 8:22 
GeneralI can't get the latest values in the gridview when updating Pin
cyeung31-Jul-08 23:06
membercyeung31-Jul-08 23:06 
GeneralRe: I can't get the latest values in the gridview when updating Pin
Ashrafur Rahaman1-Aug-08 0:48
memberAshrafur Rahaman1-Aug-08 0:48 
GeneralRe: I can't get the latest values in the gridview when updating Pin
cyeung3-Aug-08 15:48
membercyeung3-Aug-08 15:48 
GeneralI am having same problem Pin
DukeCylk12-Dec-08 5:08
memberDukeCylk12-Dec-08 5:08 
AnswerRe: I can't get the latest values in the gridview when updating Pin
Member 458960622-Dec-08 22:00
memberMember 458960622-Dec-08 22:00 
GeneralRe: I can't get the latest values in the gridview when updating Pin
mgetting7-Oct-09 18:49
membermgetting7-Oct-09 18:49 
GeneralMake sure you don't FillGrid() on ever postback Pin
John Bonomi22-Jan-10 3:34
memberJohn Bonomi22-Jan-10 3:34 
GeneralRe: Make sure you don't FillGrid() on ever postback Pin
goldeneyeonline22-Feb-10 10:08
membergoldeneyeonline22-Feb-10 10:08 
GeneralRe: Make sure you don't FillGrid() on ever postback Pin
Armonds3-May-11 4:10
memberArmonds3-May-11 4:10 
GeneralTableAdoptor Pin
SamrahNed31-Jul-08 8:33
memberSamrahNed31-Jul-08 8:33 
GeneralRe: TableAdoptor Pin
Ashrafur Rahaman1-Aug-08 0:53
memberAshrafur Rahaman1-Aug-08 0:53 
QuestionTestDatabaseTableAdapters Pin
divyaseban11-Jun-08 0:09
memberdivyaseban11-Jun-08 0:09 
Questionjavascript:__doPostBack('grdHistoAttest$_ctl3$lnkAdd','') Pin
Member 115576926-May-08 22:56
memberMember 115576926-May-08 22:56 

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

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

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