Repeater中的ASP.NET DataGrid

时间:2009-10-22 02:32:43

标签: asp.net datagrid repeater

我有一个包含两列的表:

CommunityID
PersonID

还有一个“人物”表格(其中包括):

FirstName
LastName

我想为每个社区显示不同的DataGrid,每个数据网格只包含属于该社区的人员。我想这样做而不使用4个单独的SqlDataSources。

一个转发器看起来是一个很好的方式,在ItemTemplate中有一个DataGrid,但我似乎无法做出正确或反复的操作来处理每次重复的不同值。

如果有人对更好的方法有任何建议,我会非常感激,因为这是我第一次进入ASP.NET的世界

谢谢,

麦克

1 个答案:

答案 0 :(得分:13)

我个人不会使用DataGrid控件,因为它会限制您对输出的控制,并且它们已被更新的GridView& ListView控件(尽管DataGrid为not obsolete,因此如果您愿意,可以随意使用它)。您可能需要考虑使用替代方案,但不要求您这样做。

要做你正在寻找的东西,你会得到如下标记:

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

然后,您将使用以下代码隐藏连接标记:

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();
}

密钥是Repeater的ItemDataBound事件,这是每次创建转发器行时调用的方法。这是数据绑定DataGrid源的地方。您可以使用RepeaterItemEventArgs参数在此方法中放置所需的任何逻辑,以访问绑定到Repeater的数据项。

相关问题