Re: Dynamic Control Loading
Page_Load could be simplifed to
CSharp Code:
protected void Page_Load(object sender, EventArgs e) {
LoadButtons(_PageState);
}
Re: Dynamic Control Loading
I found a way to make this work but it's far from ideal. Before I add a control to the panelButtons control collection, I check to see if a control with the same text already exists.
CSharp Code:
private void LoadButtons(int pageState) {
for(int i = 0; i < pageState + 1; i++) {
Button b = new Button();
b.Text = i.ToString();
b.Click += new EventHandler(b_Click);
bool found = false;
foreach(Control ctrl in panelButtons.Controls) {
if(ctrl.GetType() == typeof(Button)) {
Button btn = (Button)ctrl;
if(btn.Text == b.Text) {
found = true;
break;
}
}
}
if(!found) {
panelButtons.Controls.Add(b);
}
}
_PageState = pageState;
}
How can this be avoided?
EDIT:
Simplified way to not insert duplicate control.
CSharp Code:
private void LoadButtons(int pageState) {
for(int i = 0; i < pageState + 1; i++) {
Button b = new Button();
b.ID = this.ID + "_button_" + i.ToString();
b.Text = i.ToString();
b.Click += new EventHandler(b_Click);
if(panelButtons.FindControl(b.ID) == null) {
panelButtons.Controls.Add(b);
}
}
_PageState = pageState;
}
It still seems like there should be a more straightforward way to do this.
Re: Dynamic Control Loading
Hey,
This is not a direct answer to your question by any means, but I would strongly recommend that you have a look at this article:
http://www.4guysfromrolla.com/articles/092904-1.aspx
Gary