الثلاثاء، 7 يونيو 2011

Nested ASP.NET Repeater

Steps
1.   Drag and drop to repeater control and add ItemTemplate inside the repeater.

2.   The element for the first Repeater control begins with an HTML table row () that includes a Label control. The Text attribute for the label uses the Eval method to display the name field from the data source.

3.   Next, the item template includes a Repeater control that displays the topics for the current forum. Like the first Repeater control, the data binding for this Repeater control is handled in the codebehind file.

The item template for the second Repeater control displays an HTML table row for each topic associated with the current forum. A LinkButton control is used to display the topic name. The PostBackUrl address for the link button uses the Eval method to pass the ID for the selected topic to the Threads.aspx page as a query string. For example, if the user clicks the link button for a topic whose topicid is 4, the PostBackUrl will be Threads.aspx?topic=4.


The code-behind file for the Forum Home page


public partial class _Default : System.Web.UI.Page
{
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ForumConnectionString"].ConnectionString);       
        ds = new DataSet();
        // fill the Forums table
        string sel = "SELECT [forumid], [name] " + "FROM Forums " + "ORDER BY [name]";
        SqlDataAdapter da = new SqlDataAdapter(sel, con);
        da.Fill(ds, "Forums");

        // fill the Topics table
        sel = "SELECT [forumid], [topicid],[name], [description] FROM Topics ORDER BY [name]";
        da = new SqlDataAdapter(sel, con);
        da.Fill(ds, "Topics");
        // bind the Forum repeater
        ForumRepeater.DataSource = ds.Tables["Forums"].DefaultView;
        ForumRepeater.DataBind();
    }


protected void ForumRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //FindControl method to find the Repeater control named TopicRepeater
        Repeater r = ((Repeater)e.Item.FindControl("TopicRepeater"));

        //e.Item.DataItem is used to retrieve a DataRowView object
        //that lets you access the individual data fields for the Repeater item.

        DataRowView drv = (DataRowView)e.Item.DataItem;
        string forumid = drv["forumid"].ToString();
       
        //retrieve a DataView object for the Topics table of
        //the data set and set its row filter so it views only those rows
        //whose forumid field matches the value of the forumid variable 
        DataView dv = ds.Tables["Topics"].DefaultView;
        dv.RowFilter = "forumid=" + forumid;
        r.DataSource = dv;
        r.DataBind();
    }
}




0 التعليقات: