Click here to Skip to main content
Click here to Skip to main content
Go to top

GridView-FormView (Master/Detail) Control

, 24 Feb 2009
Rate this:
Please Sign up or sign in to vote.
Full-featured GridView-FormView with View/Insert/Update features
Sample Image - screen0.jpg

Introduction

The GridViewFormView control is an ASP.NET user control that displays a fully-featured GridView-FormView (Master/Detail) control with the capability to edit existing records, insert new records, and delete records, along with sorting, filtering, and paging. The control can be easily configured to allow record inserting/editing in the GridView control or in the FormView control after a record is selected.

This control demonstrates some of the more clearer ways of editing, inserting, and deleting records with a Master/Detail control in an N-Tier environment, in which data objects and business objects are used with a GridView-FormView to load and store data.

Background

I recently had a project in which I needed to manage some datatables via gridviews, but the number of columns in the table was too large to be handled nicely with in-grid editing. After looking into the new DetailsView control, I found that it would meet the requirements, except that the fields could not be positioned in the form as the requirements specified. One of the primary differences between the FormView control and the DetailsView control is that the template fields can be positioned by HTML, instead of just in a template definition. Coupling the GridView together with a FormView control presented a good solution to the problem.

When I Googled around for samples on having a GridView work together with a FormView control, I would find a code snippet here and there that did part of what I needed, but few real-world examples of the two controls together. This article/control is an attempt in providing such a solution.

Using the GridViewFormView UserControl

To use the GridViewFormView 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 GridViewFormView'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 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 GridViewFormView 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. along with whether you want the record-editing to be performed in the FormView or the GridView control.

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 GridViewFormView. 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 Order Details 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 GridViewFormView sample:

Basic View of the GridView Control

GridView View

Editing a Record in the GridView Control

GridView Editing

Inserting a Record in the GridView Control

GridView Inserting

Basic View of the FormView Control

FormView View

Editing a Record in the FormView Control

FormView Editing

Inserting a Record in the FormView Control

FormView Inserting

How the GridViewFormView Control Works

The GridViewFormView control is basically just an instance of a GridView control and the FormView control wrapped within a single user control, which exposes a number of properties that can be used to enable/disable various features. The GridView control and the FormView control are both on separate panels, only one of which is visible at any given time.

The FormView panel is hidden by default, and when a record is selected in the GridView, the record is bound to the FormView control and the views are swapped, so the GridView panel is hidden while the FormView panel is made visible. The user can return to the GridView display at any time by clicking the "Return to OrdersList" link button.

Below are some of the more useful code-snippets used in the control to read/write data between the business objects and the GridView control and the FormView control.

/// <summary>
/// Initialize the member variables and bind the gridview/FormView
/// </summary>
public void Initialize()
{
    AllowGridViewRecordSorting = true;
    AllowGridViewRecordDeleting = true;
    AllowGridViewRecordEditing = true;
    AllowGridViewRecordInserting = true;
    AllowGridViewRecordSelection = true;
    AllowFormViewRecordDeleting = true;
    AllowFormViewRecordEditing = true;
    AllowFormViewRecordInserting = true;
    ForceEditsInFormView = false;
    GridViewEditControlsVisible = false;
    ClearDataViews();
    BindDataViews();
}
/// <summary>
/// Initiates a filtered search
/// </summary>
///
public void SearchRecords(string _SearchFilter)
{
    SearchFilter = _SearchFilter;
    BindDataViews();
}
...
...
...
/// <summary>
/// Sets the new ViewMode for the control and updates the display accordingly
/// </summary>
///
protected void SetBehavior(ViewMode vmNewViewMode)
{
    m_ViewMode = vmNewViewMode;
    SetBehavior();
}
/// <summary>
/// Handles the display of the gridview/FormView controls according to the ViewMode
/// </summary>
protected void SetBehavior()
{
    bool bHasGridRows = (gvOrders.Rows.Count > 0);
    if ((bHasGridRows == false) && (AllowFormViewRecordInserting == true))
    {
        m_ViewMode = ViewMode.FormView;
    }
     switch (m_ViewMode)
    {
        case ViewMode.Unknown:
            pnlGridView.Visible = bHasGridRows;
            pnlFormView.Visible = !bHasGridRows;
            break;
        case ViewMode.GridView:
            pnlGridView.Visible = true;
            pnlFormView.Visible = false;
            break;
        case ViewMode.FormView:
            pnlGridView.Visible = false;
            pnlFormView.Visible = true;
            break;
    }
    lbtnGridInsertOrders.Visible = GridViewEditControlsVisible;
    lbtnGridCancelOrders.Visible = GridViewEditControlsVisible;
    gvOrders.ShowFooter = GridViewEditControlsVisible;
    lbtnAddNewOrders.Visible = (AllowGridViewRecordInserting &&
    !GridViewEditControlsVisible &&
    !pnlFormView.Visible);
    lbtnReturnToOrdersList.Visible = bHasGridRows;
}
/// <summary>
/// Clears out the binding of the old data
/// </summary>
protected void ClearDataViews()
{
    gvOrders.DataSource = null;
    gvOrders.DataBind();
     fvOrders.DataSource = null;
    fvOrders.DataBind();
}
/// <summary>
/// Binds the gridview/FormView controls - this overload will display
/// the records in a gridview
/// </summary>
protected void BindDataViews()
{
    gvOrders.ShowFooter = (AllowGridViewRecordInserting &&
	GridViewEditControlsVisible);
    BindDataViews(0);
}
/// <summary>
/// Binds the gridview/formview controls - if primarykey is specified,
/// the formview is used
/// </summary>
///
protected void BindDataViews(int _OrderID)
{
    CIF.Business.Northwind.Orders _Orders = new CIF.Business.Northwind.Orders();
    DataTable dtOrders = null;
    if (_OrderID > 0)
    {
        dtOrders = _Orders.GetDataTable("OrderID", _OrderID.ToString());
        fvOrders.DataSource = dtOrders;
        fvOrders.DataBind();
        SetBehavior(ViewMode.FormView);
    }
    else
    {
        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
        {
            if (AllowFormViewRecordInserting == true)
            {
                fvOrders.DataSource = dtOrders;
                fvOrders.DataBind();
            }
            else
            {
                gvOrders.DataSource = null;
                gvOrders.DataBind();
            }
        }
        SetBehavior();
    }
}

Conclusion

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

License

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

Share

About the Author

Chris Hambleton
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

 
QuestionVB !!? PinmemberMember 812563529-May-12 23:03 
Questiondatabase Pinmemberkrishnasugaa26-Feb-12 22:17 
Questiontree view Pinmemberneevmansoori9-Oct-11 20:35 
GeneralMy vote of 2 Pinmemberddboarm13-Nov-10 9:09 
GeneralCould you please attach the code for CIF.Data.Northwind.dll, CIF.Business.Northwind.dll Pinmemberhossamel16-Oct-09 21:08 
GeneralRe: Could you please attach the code for CIF.Data.Northwind.dll, CIF.Business.Northwind.dll PinmemberChris Hambleton20-Oct-09 2:44 
Generalinitialize bussiness object in detailsview PinmemberJudith Barer23-Feb-09 6:06 
GeneralRe: initialize business object in detailsview PinmemberChris Hambleton24-Feb-09 4:24 
GeneralMy vote of 2 Pinmemberpratik jain28-Dec-08 22:34 
GeneralThe Edit / Update function in the demo don't work! Pinmemberstapes27-May-08 23:57 
GeneralRe: The Edit / Update function in the demo don't work! PinmemberChris Hambleton28-May-08 4:07 
GeneralRe: The Edit / Update function in the demo don't work! Pinmemberstapes29-May-08 5:32 
GeneralIt is good stuff. Pinmembersystem.sameer.code20-May-08 4:33 
GeneralDataGrid and MultiView Pinmemberdushyantsapre31-May-07 20:15 
Questionhow we edit ,delete in grid view Pinmemberchristopehr18-Apr-07 22:19 
QuestionHelpful. Multiview? Pinmemberdlwilliams4510-Jan-07 9:17 
AnswerRe: Helpful. Multiview? PinmemberChris Hambleton10-Jan-07 17:37 
Questionand...? PinmemberMark Nischalke15-Dec-06 11:13 
AnswerRe: and...? PinmemberMichael Crandall18-Dec-06 6:01 
GeneralRe: and...? PinmemberMark Nischalke18-Dec-06 6:42 
GeneralRe: and...? Pinmembermyklk21-Nov-07 4:06 
AnswerRe: and...? PinmemberBlumen16-Jul-08 4:20 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140921.1 | Last Updated 24 Feb 2009
Article Copyright 2006 by Chris Hambleton
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid