GridView In-Place Editing Revisited

 

For my first post, I’m going to revisit an article by AzamSharp which shows a simple approach to building GridViews with add/edit/update/delete functionality and offer some suggested improvements to make it even simpler!

 

Read the original article here:

 

http://geekswithblogs.net/AzamSharp/archive/2006/01/12/65647.aspx

 

 

The original interface supports adding rows through a set of controls in the footer of the GridView. Here is the original interface.

 

Original GridView

 

While this is an excellent example of how to add controls to the footer, this interface places the add controls at the bottom of the grid. For a table with only a few rows this isn’t a problem but if there are many rows then the add row is at the bottom of the page which is an awkward position. Even worse, the user may be forced to scroll, hiding the add functionality altogether. Also, adding controls to the footer forces the coder to create ItemTemplate column definitions instead of using simpler Bound columns.

 

I would suggest moving this functionality out of the GridView to the top of the page. Here is the new look.

 

New GridView with Add functionality at top of page

 

 

To move the Add functionality out of the GridView, I’ll add a table with some textboxes and an Add button. I’ll create an event handler for the add button’s click event which will add the new user. Now that the add functionality has been moved out of the GridView, the ItemTemplates can be replaced with Bound columns and we can remove the event handlers for OnRowCancelingEdit, OnRowEditing, OnRowUpdating, OnRowUpdated, OnRowDeleting and OnRowCommand. We can remove all of the code-behind event handling too since it’s no longer needed. We need to make the ID column readonly so the end user can’t change it and I’ll add the GridView tag for EmptyDataText=”No Users Found!”, just in case there are no users. Finally, I’ll add a namespace for the App_Code User class called myApp so User is the App_Code User and not System.Security.Principal.IPrincipal.Page.User. This also requires prefixing the TypeName attribute for the GridView with the new namespace. Here is the new Default.aspx page.

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

   

    <table>

        <tr>

            <td>First Name:</td>

            <td><asp:TextBox ID="txtAddFirstName" runat="server"></asp:TextBox></td>

        </tr>

        <tr>

            <td>Last Name:</td>

            <td><asp:TextBox ID="txtAddLastName" runat="server"></asp:TextBox></td>

        </tr>

        <tr>

            <td><asp:Button ID="Btn_Add" runat="server" Text="Add" OnClick="Btn_Add_Click" />

</td>

            <td></td>

        </tr>

    </table>

   

    <div>

        <asp:GridView DataSourceID="objUser" ID="GridView1" runat="server" AutoGenerateColumns="False"

            DataKeyNames="ID"

            EmptyDataText="No Users Found!">

            <Columns>

                <asp:BoundField HeaderText="UserID" DataField="ID" ReadOnly="true" />

                <asp:BoundField HeaderText="First Name" DataField="FirstName" />

                <asp:BoundField HeaderText="Last Name" DataField="LastName" />

                <asp:CommandField HeaderText="Edit" ShowEditButton="True" />

                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

            </Columns>

        </asp:GridView>

       

        <asp:ObjectDataSource ID="objUser" runat="server"

            DeleteMethod="DeleteUser"

            InsertMethod="AddUser"  

            SelectMethod="GetAllUsers"

            UpdateMethod="UpdateUser"

            TypeName="myApp.User">

        </asp:ObjectDataSource>

   

    </div>

    </form>

</body>

</html>

 

 

 

And here is the new Default.aspx.cs code-behind page:

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

 

    protected void Btn_Add_Click(object sender, EventArgs e)

    {

        myApp.User U = new myApp.User();

        U.AddUser(txtAddFirstName.Text, txtAddLastName.Text);

        this.GridView1.DataBind();

    }

}

 

 

And here’s the new User.cs class:

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections.Generic;

using System.Data.SqlClient;

 

namespace myApp

{

    public class User

    {

 

        .../* Remaining Code Unchanged */...

 

}//namespace myApp

 

 

 

Now that’s a simple page! I would suggest refactoring the User class with a static Add method but other than that it’s pretty clean. Anyway, I hope you like my first post. Comments and suggestions welcome!

 

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
Print | posted on Sunday, January 22, 2006 11:02 PM

Feedback

# re: GridView In-Place Editing Revisited

left by Larih at 2/6/2006 1:03 PM Gravatar
Hey, thats a good post!
quick question - Do we still need the GridView_RowUpdating function??

How do you actually pass parameters to the
UpdateMethod="UpdateUser" specified in myApp.User?

I am still a novice; more code would definitely be very helpful!

Thanks,
Larih

# re: GridView In-Place Editing Revisited

left by Brian at 2/6/2006 3:16 PM Gravatar
You no longer need the Gridview_RowUpdating function. This is replaced with the

UpdateMethod="UpdateUser"

line in the ObjectDataSource definition.

Of course, myApp.User.UpdateUser requires parameters. .Net will attempt to pass in parameters with the name of the DataField and value of the updated column when the user presses the Update button. Furthermore, .Net will add the ID field too because it is listed as one of the DataKeyNames (it's the only one in the example).

To get a better idea of how this works, try removing, renaming or adding new parameters to the UpdateUser method without changing anything else and see the errors .Net returns.

-Brian

# re: GridView In-Place Editing Revisited

left by YJ at 8/2/2006 7:30 AM Gravatar
Hi, that is a very helpful example, thanks for sharing!!

In original example, if there are no records in DB table, how to show an empty GridView with AddRecord button and table columns’ names.

Thanks

YJ

# re: GridView In-Place Editing Revisited

left by Brian at 8/2/2006 8:22 AM Gravatar
Unfortunately, there is no quick way to do this. You can set the EmptyDataText property which will replace your columns with a message, but this of couse nukes your columns. You can create a new dataset and create columns which match your columns from a "real" dataset, add a new row to your "fake" dataset with default or blank values. Then set your grid's datasource to you new fake dataset which will now contain an "empty" row and your columns and buttons show up.

I prefer to create a set of controls above my grid with an add button and not place these inside the grid for this reason. Also, using separate controls for adding allows you to put in validation controls and such. If the object is complex than I create an add link which goes to an Add page. Saving or canceling from the Add page returns the user to the page with the grid. This interface seems to work well.

# re: GridView In-Place Editing Revisited

left by Sunil Latthe at 8/8/2007 11:53 PM Gravatar
Hi,Actually i have same requirement which u mentioned in this article.But i am facing one problem in updating the data.As u said updatemethod call by .net and also passes the parameter of datafield for me when i click update button it giving me error that gridview_updating event not handled.please give solution of send me your code of this article.I strucked here ,expected reply very early,Thanks

# re: GridView In-Place Editing Revisited

left by Abdul Hannan at 11/2/2011 3:20 AM Gravatar
This is really good article and its helps me very much. Thank you brian. Regards.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: