-->

How to enable in-place editing with validation control in a GridView in ASP.NET


Introduction

In this post, I am going to explain how to enable in-place editing with validation control in a GridView in ASP.NET

The GridView control allows editing on a row-by-row basis. Here I am writing this article to explain how to enable in-place editing with validation control in a GridView in ASP.NET.


Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for Show Data in Gridview which rows are editable.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
              <h3>Inline Edit / Delete with validation control in Gridview in ASP.NET</h3>
                <br />
                <div>
                    <asp:GridView ID="gvContact" runat="server" AutoGenerateColumns="false" CellSpacing="5" CellPadding="5" 
                        DataKeyNames="ContactID"
                        OnRowCancelingEdit="gvContact_RowCancelingEdit" 
                        OnRowDeleting="gvContact_RowDeleting" 
                        OnRowEditing="gvContact_RowEditing" 
                        OnRowUpdating="gvContact_RowUpdating">
                        <Columns>
                            <asp:TemplateField HeaderText="SL No.">
                                <ItemTemplate>
                                    <%#Container.DataItemIndex + 1 %>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Contact Person">
                                <ItemTemplate>
                                    <%#Eval("ContactPerson") %>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtContactPerson" runat="server" Text='<%#Bind("ContactPerson") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rftxtContactPerson" runat="server" 
                                        ControlToValidate="txtContactPerson" ForeColor="Red" SetFocusOnError="true"
                                        ErrorMessage="Please provide Contact Person." ValidationGroup="Update">*</asp:RequiredFieldValidator>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Contact No">
                                <ItemTemplate>
                                    <%#Eval("ContactNo") %>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtContactNo" runat="server" Text='<%#Bind("ContactNo") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rftxtContactNo" runat="server" 
                                        ControlToValidate="txtContactNo" ForeColor="Red" SetFocusOnError="true"
                                        ErrorMessage="Please provide Contact No." ValidationGroup="Update">*</asp:RequiredFieldValidator>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Email ID">
                                <ItemTemplate>
                                    <%#Eval("EmailID") %>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtEmailID" runat="server" Text='<%#Bind("EmailID") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="rgtxtEmailID" runat="server" 
                                        ControlToValidate="txtEmailID" ForeColor="Red" SetFocusOnError="true"
                                        ErrorMessage="Please provide valid email id." ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <%-- This is for Show Edit & Delete Button  --%>
                                <ItemTemplate>
                                    <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" 
                                        CommandArgument='<%#Eval("ContactID")%>'>Edit</asp:LinkButton>
                                    &nbsp;
                                    <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete"
                                        CommandArgument='<%#Eval("ContactID") %>' 
                                        OnClientClick="javascript: return confirm('Are you really want to delete?')">Delete</asp:LinkButton>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <%-- This is for show Update & Cancel Button after click on Edit Button (Edit Mode) --%>
                                    <asp:LinkButton ID="lbtnUpdate" runat="server" CommandName="Update" 
                                        CommandArgument='<%#Eval("ContactID")%>'>Update</asp:LinkButton>
                                    &nbsp;
                                    <asp:LinkButton ID="lbtnCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                                </EditItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </div>
        

Step-6: Write following code in Page_Load event for Show data in Gridview.


             protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    PopulateData(); // Populate All Contacts from Database and show in gridview
                }
            }
        
Here is the function...
            private void PopulateData()
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    gvContact.DataSource = dc.Contacts.ToList();
                    gvContact.DataBind();
                }
            }
        

Step-7: Write below code in Gridview RowEditing event for make particular row editable.


             protected void gvContact_RowEditing(object sender, GridViewEditEventArgs e)
            {
                // This event is for open edit item templete for particular row
            
                gvContact.EditIndex = e.NewEditIndex;
                PopulateData();
            }
        

Step-8: Write below code in Gridview RowCancelingEdit event for cancel row editing.


             protected void gvContact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
            
                // This event is for cancel editing
                gvContact.EditIndex = -1;
                PopulateData();
            }
        

Step-9: Write below code in Gridview RowDeleting event for delete record from database.


             protected void gvContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                // This event is for Deleting for particular row
                int ContactID = Convert.ToInt32(gvContact.DataKeys[e.RowIndex]["ContactID"].ToString());
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    var c = dc.Contacts.Where(a => a.ContactID.Equals(ContactID)).FirstOrDefault();
                    if (c!= null)
                    {
                        dc.Contacts.Remove(c);
                    }
                    dc.SaveChanges();
                    PopulateData();
                }
            }
        

Step-10: Write below code in Gridview RowUpdating event for update database record.


             protected void gvContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                // Here I will update record
                int ContactID = Convert.ToInt32(gvContact.DataKeys[e.RowIndex]["ContactID"].ToString());

                // Find Textbox for get updated values
                TextBox txtContactPerson = (TextBox)gvContact.Rows[e.RowIndex].FindControl("txtContactPerson");
                TextBox txtContactNo = (TextBox)gvContact.Rows[e.RowIndex].FindControl("txtContactNo");
                TextBox txtEmailID = (TextBox)gvContact.Rows[e.RowIndex].FindControl("txtEmailID");

                if (txtContactPerson != null && txtContactNo != null && txtEmailID != null)
                {
                    if (txtContactPerson.Text.Trim() != "" && txtContactNo.Text.Trim() != "")
                    {
                        using (MyDatabaseEntities dc = new MyDatabaseEntities())
                        {
                            Contact c = dc.Contacts.Where(a => a.ContactID==ContactID).FirstOrDefault();
                            if (c != null)
                            {
                                c.ContactPerson = txtContactPerson.Text.Trim();
                                c.ContactNo = txtContactNo.Text.Trim();
                                c.EmailID = txtEmailID.Text.Trim();

                                dc.SaveChanges();
                            }                        
                        }
                        PopulateData();
                    }
                }
            }
        

Step-11: Run Application.


Related Post : 
  1. How to load gridview rows on demand from database through scrolling in ASP.NET
  2. How to implement Custom Paging in ASP.Net GridView using SQL Server Stored Procedure
  3. How to Marge Gridview adjacent cells depending on cells value in ASP.NET
  4. How to group columns in gridview header row in ASP.NET (programmer friendly way)
  5. Implementing cascading DropDowndivst in GridView in ASP.NET with out Web Service, Ajax.
  6. CheckBox inside GridView and handle its events to get records based on its Checked state.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.