I have a repeater that creates n-number of panels. I am trying to dynamically add different controls to each of the panels. I may very well be going about this the wrong way.
My code is more or less:
.aspx:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<% Response.Write("<asp:panel runat=\"server\" id=\"uxPanel_"); %>
<%# DataBinder.Eval(Container.DataItem, "TableId")%><% Response.Write("\"></asp:panel>"); %>
</ItemTemplate>
</asp:Repeater>
.cs:
public partial class class1: System.Web.UI.Page
{
DataSet ds= null;
protected void Page_Load(object sender, EventArgs e)
{
GetRecords(1,1);
}
protected void GetRecords()
{
ds= dal.LoadRecords();
this.Repeater1.DataSource = ds.Tables[0];
this.Repeater1.DataBind();
Literal lit = new Literal();
lit.Text = "Some text";
this.FindControl("uxPanel_1").Controls.Add(lit);
}
}
Just to be clear in thi开发者_开发技巧s example "dal.LoadRecords" is simply call to a method that retrieves some records from a DB.
I think my problem is how I am adding my panels in the first place, but this seemed like an easy way to have them uniquely named.
Any Pointers?
Thanks
As the previous answerer has said, this is fraught with peril!
If you must: I should ditch the repeater approach altogether.
Create a container panel or placeholder and in the code behind dynamically add your panels to that using ContainerPanel.Controls.Add(newPanel);
Your child "panel" could be a UserControl if needs be too.
Be aware that you'll have to regenerate your dynamic controls on postback.
Pointers? Yes : Don't dynamically add controls!
Dynamically adding controls adds a lot of overhead and you run into issues with viewstates. Usually , it's not worth the time and headaches.
Panels, as well as Literals, PlaceHolders, and every other ASP.NET control have a Visible property that you can toggle on and off, like so:
myPanel.Visible=true;
myOtherPanel.Visible = false;
myTogglePanel.Visible = ! myTogglePanel.Visible; //toggle it's visibility
This approach is much, much easier.
精彩评论