I’m creating a usercontrol that will have a series of LinkButtons.
I’ve declared all of my link buttons at the top of my class
LinkButton LB1 = new LinkButton();
LinkButton LB2 = new LinkButton();
//...
LinkButton LB9 = new LinkButton();
now I’d like to be able to create a loop to access all of those link buttons so I don’t have to write them all out every time.
I tried something like this within my overridden CreateChildControls() method:
for (int i = 1; i < 10; i++)
{
LinkButton lb = (LinkButton)FindControl("LB" + i.ToString());
lb.Text = i.ToString() + "-Button";
}
I keep getting an exception saying that lb.Text… is not set to an instance of an object.
I also tried giving all of my LB1, LB2 etc valid Ids.
ie: LB1.ID = “LB1”;
still not dice.
how can I do this?
FindControlonly works once those controls have been added toControlscollection, and that only happens inside theOnInitmethod. So you’re getting an exceptions because the LB1, LB2, etc controls haven’t been added to the Controls collection and FindControl is returningnull.One way you could do it is have a
List<LinkButton>, then in yourInitevent handler, add the controls to the list.Another way, you could use LINQ to loop through your child controls:
This version would return all
LinkButtoncontrols, so I’m not sure if that’s exactly what you want. Again, this would only work in theInitevent or later in the page cycle.Additionally
Depending on how your page is structure, you might be better off using a Repeater control. Something like this on your .aspx/ascx file:
Then in your code behind, you’d use data-binding to set up the array and so on.