开发者

ASP.NET DataGrid within a Repeater

开发者 https://www.devze.com 2022-12-08 22:45 出处:网络
I have a table that has two columns: CommunityID PersonID And A \"People\" table that has (among other things):

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 communit开发者_JAVA技巧y. 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消