Click here to Skip to main content
15,039,470 members
Articles / Web Development / HTML5
Tip/Trick
Posted 13 Jul 2011

Stats

82.2K views
19 bookmarked

Nested GridView controls in ASP.NET: best practices

Rate me:
Please Sign up or sign in to vote.
4.90/5 (8 votes)
30 Oct 2011CPOL2 min read
ASP.NET GridView control hosting another GridView in data-centric web applications

General solution


Nesting GridView controls in ASP.NET were described in that almost “canonical” Microsoft walkthrough [1]. In general, it requires creating of two GridView controls: the first one serving as a container or master GridView1 with its own DataSource1 (SqlDataSource, AccessDataSource, etc.) and second "nested" GridView2 with its underlying DataSource2 residing within a TemplateField in master GridView1.

Code snippet [1] inside the GridView1 RowDataBound event procedure (GridView1_RowDataBound) serves the task of passing a "foreign key" value from GridView1 to DataSource2. In the particular example provided in [1], the “foreign key” stored in first cell of GridView1 (e.Row.Cells[0].Text) is passed to DefaultValue property of only one SelectParameter (SelectParameters[0]) of SqlDataSource2:

Listing 1. Original solution on MSDN w/hardcoded Cells index


C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    SqlDataSource s = (SqlDataSource)e.Row.FindControl("SqlDataSource2");
    s.SelectParameters[0].DefaultValue = e.Row.Cells[0].Text;
  }
}


This should work in all practical versions of ASP.NET (2.0/3.5/4.0). However, the potential drawback of this solution rises from the fact that the foreign key value (for example, ID) could be omitted from visible fields set of GridView1 control. Also, even in case this foreign key field is presented in GridView1, then there is potential inconvenience of hard-coded Cell index of 0; generally, it can be not the first one in the field set and, also, its index could change dynamically during the data table editing operations or as a result of dynamically re-arranging table columns order.

Better solution


Better solution shown in the following Listing 2 effectively resolves all of those potential issues described above by using named DataKeys in GridView1 control to be used as a "foreign keys" for second DataSource. In this particular example, DataKey Composer” is added to DataKeys in GridView1 control (requires the line DataKeyNames="Composer") to be passed to corresponding select parameter s.SelectParameters[0].DefaultValue of second DataSource named “dsMusic”.

Listing 2. Improved version using DataKeys


C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
  if (e.Row.RowType == DataControlRowType.DataRow)
   {
     // find DataSource used for nested GridView (could be SqlDataSource)
     AccessDataSource s = (AccessDataSource)e.Row.FindControl("dsMusic");
     // assign parameter’s default value from the DataKeys in GridView1
     s.SelectParameters[0].DefaultValue = Convert.ToString(((GridView)sender).DataKeys[e.Row.RowIndex].Values["Composer"]);
   }
}

Note: Listing 2 demonstrates the use of ASP.NET AccessDataSource, but the concept/usage is pretty much identical to SqlDataSource.

Sample Demo


Online Music Library with attached YouTube player [2-4] is implemented using the nested GridView techniques described above: click the image below to see the working demo:

Music Library implemented as nested GridView controls

Performance Improvement


Significant performance improvement could be achieved by enabling caching for nested DataSources and using FilterParameters instead of SelectParameters. To do so:
  1. Set the nested DataSource attributes; FilterExpression="Composer ='{0}'" EnableCaching="True"
  2. Modify the event procedure in Listing 2 by replacing the line assigning SelectParameters with the following one:
    // assign filter parameter default value from the datakey
    s.FilterParameters[0].DefaultValue = Convert.ToString(((GridView)sender).DataKeys[e.Row.RowIndex].Values["Composer"]);

... and voila (that's it!)

References



  1. Walkthrough: Creating a Nested GridView Control[^]
  2. Music Library implemented as nested GridView controls [^]
  3. YouTube™ API for ASP.NET[^]
  4. YouTube™ Embedded Video Player: Extended API (C#)[^]

License

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

Share

About the Author

DrABELL
Software Developer (Senior)
United States United States
Dr. Alexander Bell is a seasoned full-stack Software Engineer (Win/Web/Mobile). He holds PhD in Electrical and Computer Engineering, authored 37 inventions and published 300+ technical articles. Currently focused on multiple Android/Mobile development projects and Big Data' Machine Learning, AI, IoT. Alex participated in App Innovation Contests (AIC 2102/2013) with multiple winning submissions. Sample portfolio apps and publications:

  1. Publications by A. Bell
  2. Educational Web Portal
  3. Engineering Calculator VOLTA
  4. Aggregate Product function extends SQL
  5. Use SQL to generate large data sequence
  6. HTML5/CSS3 graphic enhancement: buttons, inputs
  7. Advanced CSS3 Styling of HTML5 SELECT Element
  8. enRoute: Real-time NY City Bus Tracking Web App
  9. YouTube™ API for ASP.NET
  10. HTML5 Tables Formatting: Alternate Rows, Color Gradients, Shadows

Comments and Discussions

 
Questionnot full Pin
tinhdamsugia10-May-13 5:27
Membertinhdamsugia10-May-13 5:27 
AnswerRe: not full Pin
DrABELL10-May-13 6:46
professionalDrABELL10-May-13 6:46 
Generalthis example is so useful for me! vote = 5 star! Pin
taha bahraminezhad Jooneghani1-Nov-11 15:06
Membertaha bahraminezhad Jooneghani1-Nov-11 15:06 
GeneralRe: Many Thanks for your note/vote. Pin
DrABELL18-Jan-12 7:37
professionalDrABELL18-Jan-12 7:37 
Generalthe solution you propose is nice. however you can solve all ... Pin
HalfHuman21-Sep-11 5:13
MemberHalfHuman21-Sep-11 5:13 
GeneralReason for my vote of 5 Another well written and very helpfu... Pin
BrianBissell20-Sep-11 3:03
MemberBrianBissell20-Sep-11 3:03 
GeneralRe: You're very welcome! Best regards - Alex Pin
DrABELL20-Sep-11 3:28
professionalDrABELL20-Sep-11 3:28 
GeneralReason for my vote of 5 Good example Pin
Wonde Tadesse31-Jul-11 14:43
professionalWonde Tadesse31-Jul-11 14:43 
GeneralRe: Thanks! Pin
DrABELL31-Jul-11 15:55
professionalDrABELL31-Jul-11 15:55 

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.