NewtonCode NewtonCode - 1 month ago 9
ASP.NET (C#) Question

How to dynamically bind asp.net repeater control to datasource

I have a page with a simple dropdown and repeater control in page.on submit repeater control is bound to datasource1 which has 3 columns.
Scenario 1

Now my requirement is if i select option2 , it should bind to datasource2 which contains 4 columns.
Scenario 2

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<tr>
<th align="left">Header1</th>
<th align="left">Header3</th>
<th align="left">Header2</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Header1" runat="server" /></td>
<td>
<asp:Label ID="Header3" runat="server" /></td>
<td>
<asp:Label ID="Header2" runat="server" /></td>
</tr>
</ItemTemplate>




Is it possible for the same repeater to dynamically bind to heterogeneous data sources?How can i specify the header template and item templates at run- time? Can this scenario be implemented with just one repeater control and multiple heterogeneous data sources?

Answer

Feels below code will help you .

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
    <HeaderTemplate>
        <tr class="">
            <asp:Repeater ID="Header1" runat="server">
                <ItemTemplate>
                    <th align="left"><%# Container.DataItem %>
                    </th>
                </ItemTemplate>
            </asp:Repeater>
        </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr class="">
            <asp:Repeater ID="Item1" runat="server">
                <ItemTemplate>
                    <td><%# Container.DataItem %>
                    </td>
                </ItemTemplate>
            </asp:Repeater>
        </tr>
    </ItemTemplate>
</asp:Repeater>


protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            Repeater headerRepeater = e.Item.FindControl("Header1") as Repeater;
            headerRepeater.DataSource = dt.Columns;
            headerRepeater.DataBind();
        }

       if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater columnRepeater = e.Item.FindControl("Item1") as Repeater;
            var row = e.Item.DataItem as System.Data.DataRowView;
            columnRepeater.DataSource = row.Row.ItemArray;
            columnRepeater.DataBind();
        }
    }

or in other way using 2 different User control.First user control contain repeater1, second contain repeater2.Then dynamic add these repeaters to your page, at code behind