Click here to Skip to main content
13,248,927 members (44,045 online)
Click here to Skip to main content
Add your own
alternative version


75 bookmarked
Posted 15 Dec 2006

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


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.


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;
/// <summary>
/// Initiates a filtered search
/// </summary>
public void SearchRecords(string _SearchFilter)
    SearchFilter = _SearchFilter;
/// <summary>
/// Sets the new ViewMode for the control and updates the display accordingly
/// </summary>
protected void SetBehavior(ViewMode vmNewViewMode)
    m_ViewMode = vmNewViewMode;
/// <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;
        case ViewMode.GridView:
            pnlGridView.Visible = true;
            pnlFormView.Visible = false;
        case ViewMode.FormView:
            pnlGridView.Visible = false;
            pnlFormView.Visible = true;
    lbtnGridInsertOrders.Visible = GridViewEditControlsVisible;
    lbtnGridCancelOrders.Visible = GridViewEditControlsVisible;
    gvOrders.ShowFooter = GridViewEditControlsVisible;
    lbtnAddNewOrders.Visible = (AllowGridViewRecordInserting &&
    !GridViewEditControlsVisible &&
    lbtnReturnToOrdersList.Visible = bHasGridRows;
/// <summary>
/// Clears out the binding of the old data
/// </summary>
protected void ClearDataViews()
    gvOrders.DataSource = null;
     fvOrders.DataSource = null;
/// <summary>
/// Binds the gridview/FormView controls - this overload will display
/// the records in a gridview
/// </summary>
protected void BindDataViews()
    gvOrders.ShowFooter = (AllowGridViewRecordInserting &&
/// <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;
        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.DataSource = dv;
            if (AllowFormViewRecordInserting == true)
                fvOrders.DataSource = dtOrders;
                gvOrders.DataSource = null;


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!


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


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 and he has a small web-hosting/consulting business called He has several other websites such as,, and

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

You may also be interested in...


Comments and Discussions

QuestionVB !!? Pin
Member 812563530-May-12 0:03
memberMember 812563530-May-12 0:03 
Questiondatabase Pin
krishnasugaa26-Feb-12 23:17
memberkrishnasugaa26-Feb-12 23:17 
Questiontree view Pin
neevmansoori9-Oct-11 21:35
memberneevmansoori9-Oct-11 21:35 
GeneralMy vote of 2 Pin
ddboarm13-Nov-10 10:09
memberddboarm13-Nov-10 10:09 
GeneralCould you please attach the code for CIF.Data.Northwind.dll, CIF.Business.Northwind.dll Pin
hossamel16-Oct-09 22:08
memberhossamel16-Oct-09 22:08 
GeneralRe: Could you please attach the code for CIF.Data.Northwind.dll, CIF.Business.Northwind.dll Pin
Chris Hambleton20-Oct-09 3:44
memberChris Hambleton20-Oct-09 3:44 
Generalinitialize bussiness object in detailsview Pin
Judith Barer23-Feb-09 7:06
memberJudith Barer23-Feb-09 7:06 
If you are using the detailsview to insert data and you have bound the detailsview to a business object, how can you initialize the business object when creating a new record? My business objects have default values.
Thank you
GeneralRe: initialize business object in detailsview Pin
Chris Hambleton24-Feb-09 5:24
memberChris Hambleton24-Feb-09 5:24 
GeneralMy vote of 2 Pin
pratik jain28-Dec-08 23:34
memberpratik jain28-Dec-08 23:34 
GeneralThe Edit / Update function in the demo don't work! Pin
stapes28-May-08 0:57
memberstapes28-May-08 0:57 
GeneralRe: The Edit / Update function in the demo don't work! Pin
Chris Hambleton28-May-08 5:07
memberChris Hambleton28-May-08 5:07 
GeneralRe: The Edit / Update function in the demo don't work! Pin
stapes29-May-08 6:32
memberstapes29-May-08 6:32 
GeneralIt is good stuff. Pin
system.sameer.code20-May-08 5:33
membersystem.sameer.code20-May-08 5:33 
GeneralDataGrid and MultiView Pin
dushyantsapre31-May-07 21:15
memberdushyantsapre31-May-07 21:15 
Questionhow we edit ,delete in grid view Pin
christopehr18-Apr-07 23:19
memberchristopehr18-Apr-07 23:19 
QuestionHelpful. Multiview? Pin
dlwilliams4510-Jan-07 10:17
memberdlwilliams4510-Jan-07 10:17 
AnswerRe: Helpful. Multiview? Pin
Chris Hambleton10-Jan-07 18:37
memberChris Hambleton10-Jan-07 18:37 
Questionand...? Pin
Mark Nischalke15-Dec-06 12:13
memberMark Nischalke15-Dec-06 12:13 
AnswerRe: and...? Pin
Michael Crandall18-Dec-06 7:01
memberMichael Crandall18-Dec-06 7:01 
GeneralRe: and...? Pin
Mark Nischalke18-Dec-06 7:42
memberMark Nischalke18-Dec-06 7:42 
GeneralRe: and...? Pin
myklk21-Nov-07 5:06
membermyklk21-Nov-07 5:06 
AnswerRe: and...? Pin
Blumen16-Jul-08 5:20
memberBlumen16-Jul-08 5:20 

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.

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