ASP.NET DataGrid within a Repeater

岁酱吖の 提交于 2019-12-04 11:08:04

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!