Click here to Skip to main content
15,883,809 members
Articles / Web Development / ASP.NET

Full-featured Editable GridView Control

Rate me:
Please Sign up or sign in to vote.
4.03/5 (17 votes)
14 Dec 20063 min read 189.7K   9.8K   88   16
Full-featured GridView with Edit/Insert/Update features and more!

Sample Image - screen0.jpg

Introduction

The EditableGridView control is an ASP.NET user control that displays a fully-featured GridView with the capability to edit existing grid records, insert new grid records, and delete records, along with sorting, filtering, and paging. It demonstrates some of the more clearer ways of editing, inserting, and deleting records in a GridView control in an N-Tier environment, in which data objects and business objects are used with a GridView to retrieve and store data.

Background

When I first began using the GridView/DataGrid control, I found very few samples that had all the features I needed in the projects I was working on. I would find a code snippet that does sorting, filtering, and paging, and another that does in-grid editing. However, few of the samples demonstrated precisely (and simply) how to use the GridView control in anything other than a simple demonstration project.

Using the EditableGridView UserControl

To use the EditableGridView UserControl in a web project, drop a copy of the control (both the HTML and code file) into your web project and change the name/class of the control to meet your needs. The columns and handling of the GridView's controls in the sample source are intentionally left in for the coder to easily copy/remove/modify the fields as quickly as possible, without having to start from scratch. The columns and controls used demonstrate the handling of different field types and controls, most of which are common when working with database tables and stored-procs.

In the code file, substitute your own business/data layer to load and save the GridView fields/records. Many of the supporting functions in the class can be used with any business/data object, and just a specific handful of lines of code need to be modified/removed.

To reference the control from another UserControl or a Page, don't forget to call the class's Initialize() function to set the properties for the control. You can also set the various properties in the HTML and code file to enable or disable record-editing, record-inserting, sorting, paging, etc.

Note: This control is not meant to be a stand-alone, snap-in UserControl - the intention of it is to be used as almost a "starter kit" when working with a GridView. Enhance the sections you need to use, and throw away the parts you don't need. Before running the sample demonstration, run the Orders_SPs.sql file against the Northwind database.

Note #2: Due to the foreign key constraint between the Orders table and the OrderDetails table in the Northwind database, the Delete command throws an exception from the data layer. Otherwise, the Delete command works as expected.

Below is a demonstration of several of the different views in the EditableGridView sample:

Basic View of the EditableGridView Control

GridView Basic

Editing a Record in the EditableGridView Control

GridView Editing

Inserting a Record in the EditableGridView Control

GridView Inserting

How the EditableGridView Control Works

The EditableGridView control is basically just an instance of a GridView control wrapped within a user control, which exposes a number of properties that can be used to enable/disable various features. Below are some of the useful code-snippets used in the control to read/write data between the business objects and the GridView control.

C#
/// <summary>
/// Initialize the member variables and bind the gridview
/// </summary>
public void Initialize()
{
    AllowGridViewRecordSorting = true;
    AllowGridViewRecordDeleting = true;
    AllowGridViewRecordEditing = true;
    AllowGridViewRecordInserting = true;
    AllowGridViewRecordSelection = true;

    GridViewEditControlsVisible = false;

    BindDataViews();
}

/// <summary>
/// Initiates a filtered search
/// </summary>
/// <PARAM name="_SearchFilter"></PARAM>
public void SearchRecords(string _SearchFilter)
{
    SearchFilter = _SearchFilter;
    BindDataViews();
}

...
...
...

/// <summary>
/// Handles the display of the gridview controls
/// </summary>
protected void SetBehavior()
{
    lbtnGridInsertOrders.Visible = GridViewEditControlsVisible;
    lbtnGridCancelOrders.Visible = GridViewEditControlsVisible;
    gvOrders.ShowFooter = GridViewEditControlsVisible;
    lbtnAddNewOrders.Visible = (AllowGridViewRecordInserting &&
                                !GridViewEditControlsVisible);
}

/// <summary>
/// Binds the gridview controls - this overload will display the records
/// </summary>
protected void BindDataViews()
{
    gvOrders.ShowFooter = (AllowGridViewRecordInserting &&
                            GridViewEditControlsVisible);
    BindDataViews(0);
}

/// <summary>
/// Binds the gridview controls
/// </summary>
/// <param name="_OrderID"></param>
protected void BindDataViews(int _OrderID)
{
    CIF.Business.Northwind.Orders _Orders =
               new CIF.Business.Northwind.Orders();
    DataTable dtOrders = _Orders.GetDataTable();

    if (dtOrders.Rows.Count > 0)
    {
        DataView dv = dtOrders.DefaultView;
        if ((SortExpression != string.Empty) &&
                 (SortDirection != string.Empty))
            dv.Sort = SortExpression + " " + SortDirection;

        if (SearchFilter != string.Empty)
            dv.RowFilter = SearchFilter;

        if (dv.Count <= 0)
        {
            gvOrders.DataSource = null;
            gvOrders.DataBind();
            return;
        }

        gvOrders.DataSource = dv;
        gvOrders.DataBind();
    }
    else
    {
        gvOrders.DataSource = null;
        gvOrders.DataBind();
    }

    SetBehavior();
}

/// <summary>
/// Format a date-time field according to the predefined format
/// </summary>
/// <param name="dtvalue"></param>
protected string FormatDateTime(object dtvalue)
{
    string sDateTime = Convert.ToString(dtvalue);
    if (MSCD.Utilities.Validation.IsDateTime(sDateTime) == true)
    {
        System.DateTime dt = System.DateTime.Parse(sDateTime);
        if (dt == new DateTime(1900, 1, 1))
            sDateTime = string.Empty;
        else
            sDateTime = dt.ToString(DATETIME_FORMAT);
    }

    return sDateTime;
}

/// <summary>
/// Returns the primarykey value for the specified gridrow in the gridview
/// </summary>
/// <param name="row" /></param>
/// <returns></returns>
private int GetGridViewRowOrderID(GridViewRow row)
{
    int _OrderID = 0;

    Label _ctl = (Label)row.FindControl("lblOrderID");
    if (_ctl == null)
    {
        throw new Exception("GetOrderID: could not" +
                            " find OrderID control!");
    }

    _OrderID = Convert.ToInt32(_ctl.Text);
    return _OrderID;
}

/// <summary>
/// Returns the string value for the specified textbox control in the
/// specified gridrow in the gridview
/// </summary>
/// <PARAM name="row"></PARAM>
/// <PARAM name="sControlName"></PARAM>
/// <returns></returns>
private string GetGridViewRowTextValue(GridViewRow row,
                                       string sControlName)
{
    string sFieldValue = string.Empty;

    TextBox _ctl = (TextBox)row.FindControl(sControlName);
    if (_ctl == null)
    {
        throw new Exception("GetGridViewRowTextValue: could not find " +
                               sControlName + " control!");
    }

    sFieldValue = _ctl.Text.Trim();
    return sFieldValue;
}

/// <summary>
/// Returns the string value for the specified textbox
/// control in the specified gridrow
/// </summary>
/// <PARAM name="row"></PARAM>
/// <PARAM name="sControlName"></PARAM>
/// <returns></returns>
private string GetGridViewRowDropDownListValue(GridViewRow row,
                                               string sControlName)
{
    string sFieldValue = string.Empty;

    DropDownList _ctl = (DropDownList)row.FindControl(sControlName);
    if (_ctl == null)
    {
        throw new Exception("GetGridViewRowDropDownListValue:" +
                            " could not find " +
                            sControlName + " control!");
    }

    sFieldValue = _ctl.SelectedValue;
    return sFieldValue;
}

/// <summary>
/// Returns the bool value for the specified checkbox
/// control in the specified gridrow
/// </summary>
/// <PARAM name="sControlName"></PARAM>
/// <returns></returns>
private bool GetGridViewRowCheckBoxValue(GridViewRow row,
                                         string sControlName)
{
    bool bFieldValue = false;

    CheckBox _ctl = (CheckBox)row.FindControl(sControlName);
    if (_ctl == null)
    {
        throw new Exception("GetGridViewRowCheckBoxValue:" +
                            " could not find " +
                            sControlName + " control!");
    }

    bFieldValue = _ctl.Checked;
    return bFieldValue;
}

Conclusion

I hope you find this article and control useful - it's saved me a lot of time when working with several different types of tables and datasets, and quickly getting a full-featured GridView control up and running. Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
United States United States
SOFTWARE: Chris Hambleton is a Software Developer with proven experience in developing both web and Windows client-server applications with WPF, ASP.NET, C#, SQL Server, VB.NET, Visual C++, and VB6.

Chris's website is at ChrisHambleton.com and he has a small web-hosting/consulting business called CustomersInFocus.com. He has several other websites such as EzekielWatch.com, iWriterPro.com, and BookBlitzer.com.

WRITING: He has also written several fiction books ("The Time of Jacob's Trouble" and "Endeavor in Time"), available at CWHambleton.com and of course, at Amazon.com (Full Amazon Profile).

Comments and Discussions

 
QuestionElement 'OrdersGridView' is not a known element. Pin
Member 112033288-May-16 11:08
Member 112033288-May-16 11:08 
QuestionHow to read the currnent user of the system Pin
mdazeemuddin13-Apr-09 20:44
mdazeemuddin13-Apr-09 20:44 
QuestionQuick Question Pin
anthony.tristan23-May-08 5:56
anthony.tristan23-May-08 5:56 
AnswerRe: Quick Question Pin
Chris Hambleton23-May-08 10:46
Chris Hambleton23-May-08 10:46 
QuestionMulti table update Pin
janette thurgood14-Nov-07 11:10
janette thurgood14-Nov-07 11:10 
AnswerRe: Multi table update Pin
Chris Hambleton15-Nov-07 5:04
Chris Hambleton15-Nov-07 5:04 
GeneralGetting error for date format covertion Pin
Lalithfl33-Oct-07 20:19
Lalithfl33-Oct-07 20:19 
AnswerRe: Getting error for date format covertion Pin
Chris Hambleton4-Oct-07 4:04
Chris Hambleton4-Oct-07 4:04 
GeneralRe: Getting error for date format covertion Pin
Lalithfl35-Oct-07 0:45
Lalithfl35-Oct-07 0:45 
GeneralProject Genarates the following error Pin
Karim Rabbani13-Mar-07 5:28
Karim Rabbani13-Mar-07 5:28 
GeneralRe: Project Genarates the following error Pin
Chris Hambleton14-Mar-07 4:02
Chris Hambleton14-Mar-07 4:02 
Oops - I copied part of the web.config from another project that was using the Office Libraries - you can remove that line from the web.config and the error will go away.
QuestionHow can I use it Pin
vk_taware8-Jan-07 22:49
vk_taware8-Jan-07 22:49 
AnswerRe: How can I use it Pin
Chris Hambleton9-Jan-07 16:15
Chris Hambleton9-Jan-07 16:15 
GeneralRe: How can I use it Pin
Parthasarathy Mandayam21-Nov-07 4:42
Parthasarathy Mandayam21-Nov-07 4:42 
GeneralRe: How can I use it Pin
Chris Hambleton21-Nov-07 5:14
Chris Hambleton21-Nov-07 5:14 
GeneralRe: How can I use it Pin
Parthasarathy Mandayam21-Nov-07 9:31
Parthasarathy Mandayam21-Nov-07 9:31 

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

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