Online courses in ASP.NET MVC, ASP.NET Core, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC / Core, jQuery, Angular, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Untitled 1

Edit GridView data without displaying default Edit, Update and Cancel buttons

ASP.NET GridView control provides an easy way to edit and update data with the help of CommandField column type. The default CommandField arrangement is such that the Edit, Update and Cancel buttons are displayed in a column as shown below:

The problem with this design is that the GridView edit column always occupies some screen real estate. Additionally in the edit mode the GridView expands horizontally disturbing the page layout. Luckily, with some easy trick you can render an editable GridView without displaying the default Edit, Update and Cancel buttons. For example, have a look at the following GridView:

In this GridView, there is no Edit, Update, Cancel column at all. Instead double clicking on a row takes the GridView in edit mode. There are two buttons at the top - Update and Cancel - that are common for all the rows of the GridView. They are enabled only when the GridView enters edit mode. This way you save screen space otherwise occupied by Edit, Update and Cancel column.

In order to implement this trick you need to understand how the GridView control updates its data. If you see the HTML source of a GridView once it is rendered in the browser you will find the following for Edit, Update and Cancel LinkButtons.

<a href="javascript:__doPostBack(&#39;GridView1&#39;,&#39;Edit$1&#39;)">Edit</a>
<a href="javascript:__doPostBack(&#39;GridView1$ctl02$ctl00&#39;,&#39;&#39;)">Update</a>
<a href="javascript:__doPostBack(&#39;GridView1&#39;,&#39;Cancel$0&#39;)">Cancel</a>

As you can see GridView generates the __doPostBack() calls for the Edit, Update and Cancel LinkButtons (<a> tag on the client side). The __doPostBack() call of the Edit button takes ID of the GridView as the first parameter and row number in the form Edit$<row_number> as the second parameter. The __doPostBack() call of the Update button passes the first parameter as the control's unique ID. The __doPostBack() of the Cancel button is quite similar to Edit button except that instead of Edit the command name used is Cancel. We won't go into the details of how these are generated by the GridView in this post but for the sake of our discussion it is suffice to know that the __doPostBack() calls as shown above are made when Edit, Update and Cancel links are clicked.

If you somehow generate the same script and execute it for some client side event (double click or click of a button for example) then you san essentially send the same commands to the GridView control. The easiest way to do so is to handle RowDataBound event of the GridView control as shown below:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex== GridView1.EditIndex)
            {
                //update or cancel buttons
                LinkButton updateBtn = (LinkButton)e.Row.Cells[0].Controls[0];
                string updateScript = ClientScript.GetPostBackClientHyperlink(updateBtn, "");
                Button1.Attributes["onclick"] = updateScript;

                string cancelScript = string.Format("javascript:__doPostBack('{0}','Cancel${1}')",
                                      GridView1.ID, e.Row.RowIndex);
                Button2.Attributes["onclick"] = cancelScript;
            }
            else
            {
                //edit button
                string editScript = string.Format("javascript:__doPostBack('{0}','Edit${1}')", 
                                    GridView1.ID, e.Row.RowIndex);
                e.Row.Attributes["ondblclick"] = editScript;
            }
                   
        }
        if (GridView1.EditIndex >= 0)
        {
            Button1.Enabled = true;
            Button2.Enabled = true;
        }
        else
        {
            Button1.Enabled = false;
            Button2.Enabled = false;
        }

    }
}

The RowDataBound event is raised for each and every row of the GridView while it is being data bound with the underlying data source. Let's examine this code step-by-step. The Edit, Update and Cancel buttons are displayed only for grid rows of type DataRow. They are not displayed for header or footer. Hence the "if" condition checks that the further code is executed only for RowType of DataRow.

Another "if" condition checks whether the GridView is in edit mode or read mode. This is done by checking the EditIndex property of the GridView. If EditIndex is greater than -1 it indicates that the GridView is in edit mode.

If the GridView is in edit mode you get hold of the Update and Cancel LinkButton controls rendered by the grid. This is done by accessing the Controls collection of the current row. By default Edit/Update/Cancel column is added as the first column of the grid. So, e.Cells[0] gives you the first table cell. If you have placed thhis column at some other position (end of all the other columns, for example) then you should change the index accordingly. Controls[0] gives you reference of the Update button. The ClientScript.GetPostBackClientHyperlink() method returns the client side JavaScript code that is executed when the Update button is clicked. This JavaScript code is attached to the client side click event of Button1 using its Attributes collection. Next, __doPostBack() call as needed for the Cancel button is formed using the string.Format() method and the resultant script is assigned to the click event of Button2 using its Attributes collection.

If the GridView is in read mode __doPostBack() call as needed by the Edit button is formed using string.Format() method. Since we want to take the GridView into edit mode upon double clicking on a row the Attributes collection of that row is used to wire dblclick event with this __doPostBack() call.

Button1 and Button2 are enabled only when the grid is in edit mode, otherwise they are disabled. This is done by setting the Enabled property of Button1 and Button2 accordingly.

This completes the server side coding. At this stage the GridView will enter in the edit mode if you double click on any of its DataRow. You can also update the data or cancel the edit operation by clicking on Button1 and Button2 respectively. However, the Edit column from the GridView is still visible. The final step is to hide that column so that it doesn't occupy any screen space. This can be easily done by a small jQuery code as shown below:

$(document).ready(function () {
    $("#GridView1 th:first-child").hide();
    $("#GridView1 td:first-child").hide();
});

The above jQuery code selects all the <th> and <td> elements that are first-child of their parent. That means you are selecting the first column of the GridView. Then you call hide() method to hide all these table cells. This way the entire column becomes invisible from the page.

That's it! Run the web form and test the Edit, Update and Cancel functionality.

 




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 15 Apr 2013



Tags : ASP.NET Data Access Web Forms jQuery Data Controls