views:

130

answers:

1

I have a table that has two columns:

CommunityID
PersonID

And A "People" table that has (among other things):

FirstName
LastName

I would like to display a different DataGrid for each community, each datagrid having only the people that are part of that community. I would like to do this without using 4 seperate SqlDataSources.

A Repeater looks like a good way, with a DataGrid inside the ItemTemplate, but I can't seem to make heads or tails of getting that to work with the different values for each repetition.

If anyone has any suggestions on better ways to do this, I'd be very appreciative, as this is one of my first forays into the world for ASP.NET

Thanks,

Mike

+6  A: 

Personally I wouldn't use a DataGrid control, since it restricts your control over your output and they've been replaced by the newer GridView & ListView controls (although DataGrid is not obsolete so feel free to use it if you want). You may want to consider using the alternatives but you aren't required to do so.

To do what you're looking for, you would have markup like the following:

<asp:Repeater runat="server" ID="myRepeater" 
              onitemdatabound="Repeater_ItemDataBound">
<ItemTemplate>
 <asp:DataGrid runat="server" ID="myDataGrid">
 </asp:DataGrid>
</ItemTemplate>
</asp:Repeater>

Then you'll wire up the markup with the following code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    myRepeater.DataSource = new Object[0];
    myRepeater.DataBind();
}

protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    DataGrid dg = (DataGrid)e.Item.FindControl("myDataGrid");
    object o = e.Item.DataItem;// Cast the DataItem as whatever 
                               // your Repeater's DataSource is

    // ...
    // Do whatever you need to get the 
    // data source for your DataGrid here
    // ...

    dg.DataSource = DataGridSourceObjectHere;
    dg.DataBind();
}

The key is the Repeater's ItemDataBound event, which is the method called every time a repeater row is created. This is where you can data bind your DataGrid source. You can put any logic you need to within this method using the RepeaterItemEventArgs parameter to access the data item you bound to your Repeater.

Dan Herbert
+1 for the GridView and ListView plug
rick schott
+1 well explained, with good code examples.
Chris Ballance
I don't really understand. I need my repeater to have a sqlDataSource as the source, which gets a required subset of communities. Then I need to get all people in that community. If I set up my repeater with a SqlDataSource, I get an error when I try to bind it in the Page_Load event.
Mike Trpcic
Ahh, I figured it out. Thanks for the prompt reply, it did exactly what I needed it to. +1, and accepted.
Mike Trpcic