Infolink

 

Search This Blog

Aug 30, 2012

ASP.Net Repeater dynamically using C# code

ASP.Net Repeater Databound Control can be generated dynamically using C# code. You can render the data items in dynamically generated Repeater Control. ASP.Net Panel Control can be used to add Repeater Control dynamically inside it as a child control. Method of database connectivity and Databinding using DataSource object of Repeater Control is same as we discussed in the previous article about ASP.Net Repeater Control Databinding using DataSource. While creating a dynamic Repeater control, you also have to generate its ItemTemplate, SeparatorTemplate and HeaderTemplate dynamically to display the data items retrieved from the database. In C# code behind use the DataSource object to bind the data with dynamic Repeater Control and add it as a child control of ASP.Net Panel to render all stuff on the web page.

HTML Code to Generate ASP.Net Repeater Control Dynamically

<asp:Panel ID="Panel1" runat="server">  
</asp:Panel> 

C# Code to Generate ASP.Net Repeater Control Dynamically


// Repeater Control Databinding using Datasource  
Repeater Repeater1 = new Repeater();  
Repeater1.DataSource = myDataSet;  
Repeater1.DataBind();  
  
foreach (RepeaterItem repeatItem in Repeater1.Items)  
{  
    // if condition to add HeaderTemplate Dynamically only Once  
    if (repeatItem.ItemIndex == 0)  
    {  
        RepeaterItem headerItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Header);  
        HtmlGenericControl hTag = new HtmlGenericControl("h4");  
        hTag.InnerHtml = "Employee Names";  
        repeatItem.Controls.Add(hTag);  
    }  
  
    // Add ItemTemplate DataItems Dynamically  
    RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);  
    Label lbl = new Label();  
    lbl.Text = string.Format("{0} {1} <br />", myDataSet.Tables[0].Rows[ repeatItem.ItemIndex ]

    [ "FirstName" ], myDataSet.Tables[0].Rows[ repeatItem.ItemIndex ][ "LastName" ]);  
    repeatItem.Controls.Add(lbl);  
  
    // Add SeparatorTemplate Dynamically  
    repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Separator);  
    LiteralControl ltrlHR = new LiteralControl();  
    ltrlHR.Text = "<hr />";  
    repeatItem.Controls.Add(ltrlHR);  
}  
  
// Add Repeater Control as Child Control  
// of Panel Control  
Panel1.Controls.Add(Repeater1);


2 comments:

  1. very informative. Thanks.

    take a look into this article for beginners http://www.etechpulse.com/2014/04/aspnet-repeater-control-c-example.html

    ReplyDelete
  2. Thanks! Great website, very useful .

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...