Nested Repeaters in ASP.NET

Ok so you may want to show some hierarchical data using repeaters. This means nesting a repeater in a repeater. This is fine but it takes some work in the code behind. First off create the main repeaters ItemDataBound event. In that event use the following code. I am old school so forgive me any syntax. For this code to work you must originally bind a DataSet to the parent repeater with a data relation connecting the parent/child tables.

So somewhere (I do mine in page load) bind the entire dataset to the repeater:


RepeaterCapabilities.DataSource = someDataSet;
RepeaterCapabilities.DataBind();


Then put the following code in the repeaters ItemDataBound event




protected void RepeaterCapabilities_ItemDataBound( object sender, RepeaterItemEventArgs e )
{
Repeater rptActivities;

DataRowView drv;

// get the row behind the databind
drv = e.Item.DataItem as DataRowView;

if( drv != null )
{
// get the nested repeater
rptActivities = e.Item.FindControl( "RepeaterActivities" ) as Repeater;

// check for a valid control
if( rptActivities != null )
{
// create a child view and bind it, the relation name must be there for the PK/FK link to work
rptActivities.DataSource = drv.CreateChildView( "CapAndActRelationship" );
rptActivities.DataBind();
}//end if
}//end if
}

Comments

Anonymous said…
Nice article!

I read 10 articles on how to do this and they all sound greek... people rambling on for 2-3 paragraphs about basic SQL and cluttering up the information.

I read yours, and in about 30 seconds understand what I am supposed to do.

Nice job!
jlechem said…
Thanks I'm glad I was able to help out! It's always nice getting a note from a reader who got something useful out of my posts.
Anonymous said…
Thanks Justin - helped me too! Next time though it would be extra helpful if you could put it in to a complete example page with all the other code included. This helps to put it in to context for dummies like me... :)
Thank you! You hit it just right.
Tom L said…
Excellent article. I'd wasted the past four hours wading through inaccurate and incoherent articles which didn't explain things clearly and worse, didn't offer a working solution!

Your explanation is a beauty of brevity.

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC