Click here to Skip to main content
6,293,171 members and growing! (12,169 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » Grid Controls     Intermediate License: The Code Project Open License (CPOL)

Editable GridView in ASP.NET 2.0

By Ashrafur Rahaman

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
C#, .NET (.NET 2.0), ASP.NET, SQL Server (SQL 2005), Dev
Posted:6 Feb 2008
Updated:7 Feb 2008
Views:103,218
Bookmarked:62 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
23 votes for this article.
Popularity: 5.06 Rating: 3.72 out of 5
3 votes, 13.0%
1

2
2 votes, 8.7%
3
4 votes, 17.4%
4
14 votes, 60.9%
5

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

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

License

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

About the Author

Ashrafur Rahaman


Member
Lead programmers on project to finish the outsourced product, analyze requirement and define solution architecture for project. Design and maintain database. Software quality assurance, source control, bug tracking, feature and project schedule planning. Developed Statement of Work, setup project plan, designed Data Model and Web Application architecture in .NET 2.0/3.5 and SQL Server, and supervise a .net developer’s team.
Occupation: Team Leader
Company: Latitude-23
Location: Bangladesh Bangladesh

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 60 (Total in Forum: 60) (Refresh)FirstPrevNext
GeneralDB Script. Pinmemberjaved_alam7861:01 30 Jun '09  
GeneralWhere is the database boss? PinmemberJags12122:40 1 May '09  
GeneralRe: Where is the database boss? Pinmemberjahirhstu16:42 16 May '09  
GeneralTable Design of Contact and ContactType Pinmemberchemlms8:44 9 Jan '09  
Generaladding validation Pinmembermgetting20:11 3 Dec '08  
Generalproblem with imagebutton instead of linkbutton PinmemberXildur9:22 12 Oct '08  
Generalinput string invalid on ddl [modified] Pinmembermgetting18:06 4 Aug '08  
GeneralGreat Article (Ported To VB) Pinmemberaderoun9:19 3 Aug '08  
GeneralRe: Great Article (Ported To VB) PinmemberAshrafur Rahaman10:00 3 Aug '08  
GeneralI can't get the latest values in the gridview when updating Pinmembercyeung0:06 1 Aug '08  
GeneralRe: I can't get the latest values in the gridview when updating PinmemberAshrafur Rahaman1:48 1 Aug '08  
GeneralRe: I can't get the latest values in the gridview when updating Pinmembercyeung16:48 3 Aug '08  
GeneralI am having same problem PinmemberDukeCylk6:08 12 Dec '08  
AnswerRe: I can't get the latest values in the gridview when updating PinmemberMember 458960623:00 22 Dec '08  
GeneralTableAdoptor PinmemberSamrahNed9:33 31 Jul '08  
GeneralRe: TableAdoptor PinmemberAshrafur Rahaman1:53 1 Aug '08  
QuestionTestDatabaseTableAdapters Pinmemberdivyaseban1:09 11 Jun '08  
Questionjavascript:__doPostBack('grdHistoAttest$_ctl3$lnkAdd','') PinmemberMember 115576923:56 26 May '08  
GeneralFooter dropdown selected index changed event Pinmemberdownloading.acoount4:55 22 Apr '08  
AnswerRe: Footer dropdown selected index changed event PinmemberAshrafur Rahaman9:29 22 Apr '08  
GeneralRe: Footer dropdown selected index changed event Pinmemberdownloading.acoount8:07 23 Apr '08  
Generalupdation problem PinmemberNeetu Maheshwari1:41 21 Apr '08  
AnswerRe: updation problem PinmemberAshrafur Rahaman2:40 21 Apr '08  
GeneralTestDatabaseTableAdapters; Pinmemberkankmonty21:19 16 Apr '08  
AnswerRe: TestDatabaseTableAdapters; PinmemberAshrafur Rahaman21:39 16 Apr '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 Feb 2008
Editor: Smitha Vijayan
Copyright 2008 by Ashrafur Rahaman
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project