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
}
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
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!
Your explanation is a beauty of brevity.