Wednesday, August 10, 2011

Nested Repeater in asp.net

No comments:


--Tables used.


CREATE TABLE [dbo].[user_types](
[ut_id] [int] IDENTITY(1,1) NOT NULL,
[ut_name] [varchar](50) NULL
)
------------------------
CREATE TABLE [dbo].[users](
[u_id] [int] IDENTITY(1,1) NOT NULL,
[u_ut_id] [int] NULL,
[u_name] [varchar](50) NULL,
[u_password] [varchar](50) NULL
)
-------------------------

Default.aspx

<body>
    <form id="form1" runat="server">
    <div>
    <%@ Import Namespace="System.Data" %>
        <h1 style="background-color:Lime;">Nested Repeater</h1>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <h2 style="background-color:Aqua;" >Children of <%# DataBinder.Eval(Container.DataItem, "ut_name")%></h2>
                <asp:Repeater ID="Repeater2" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("typerelation") %>' runat="server">
                    <ItemTemplate>
                        <h3 style="background-color:Olive;">child item <%# DataBinder.Eval(Container.DataItem, "[\"u_name\"]")%></h3>
                    </ItemTemplate>
                </asp:Repeater>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>

-----------------------------

Default.aspx.cs

using System.Data;
using System.Data.SqlClient;


protected void Page_Load(object sender, EventArgs e)
    {
        DataSet DsRep = new DataSet();
        SqlCommand SqlCmd = new SqlCommand();
        DataTable DtRep;
        string con = @"Server=.\SQLEXPRESS; Database=tutorials; uid=sa; pwd=asdf123*;";
        string command = "";


        command = "select ut_id,ut_name from user_types";
        DtRep = new DataTable();
        new SqlDataAdapter(command, con).Fill(DsRep, "parent");
     
        command = "select u_id,u_ut_id,u_name from users";
        DtRep=new DataTable();
        new SqlDataAdapter(command, con).Fill(DsRep, "child");


        DsRep.Relations.Add("typerelation", DsRep.Tables["parent"].Columns["ut_id"], DsRep.Tables["child"].Columns["u_ut_id"]);


        Repeater1.DataSource = DsRep.Tables[0];
        Page.DataBind();
    }