Big question about code-generated buttons at page load VERSUS manually-added buttons in design view.
You can't manually add 140 buttons, so I prefer code. All buttons will behave similarly at button click (they will change colour). I can't obviously write 140 click event methods, so how can I make a general event that can work for all?
I thought of doing this:
protected void btn_Click(object sender, EventArgs e)
{
Button btn1 = Panel2.FindControl("btn") as Button;
btn1.BackColor = Color.Red;
}
Because all buttons are called btn.
This is how I add buttons:
for (int a = 1; a <= 10; a++)
{
for (char b = 'A'; b <= 'N'; b++)
{
btn = new Button();
btn.Text = "";
btn.Height = 20; btn.Width = 20;
btn.ToolTip = a + " " + b;
Panel2.Controls.Add(btn);
}
Panel2.Controls.Add(new LiteralControl("<br/>")); // this inserts a paragraph
}
I don't know if btn_Click(object sender, EventArgs e)
works, because after I click a button all disappear. How can I fix that?
At the end, I need to count how many buttons are red. Is my following idea practical? We know how to find the Button control called "btn", but how do I find "a button with a certain property, for example find button named btn with tooltip=1A. I would go through all the tooltips (1A, ... 10N) and check each button (considering they have unique tooltips), and check the color each time. For each red color, I count a button.
Is it a problem is they are all called "btn"? For now I can differentiate them by tooltip: 1A, 1B, ...10N, as I said. Thanks a lot.
EDIT>>>>>>> I tried Ben's advice and the problem is now that all the buttons disappear when I click any of them. Thanks for yoru patience.
public partial class Seatalloc2 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateControls();
}
}
protected void PopulateControls()
{
Panel1.Visible = true;
Button btn;
Panel2.Visible = true;
DropDownList nrbileteddl = Panel1.FindControl("nrBileteddl") as DropDownList;
nrbileteddl.Visible = true;
for (int i = 1; i <= 5; i++)
{
nrbileteddl.Items.Add(i + "");
}
for (int a = 1; a <= 10; a++)
{
for (char b = 'A'; b <= 'N'; b++)
{
btn = new Button();
btn.Text = "";
btn.Height = 20;
btn.Width = 20;
btn.ToolTip = a + " " + b;
btn.BackColor = Color.Green;
btn.Click += new EventHandler(btn_Click);
Panel2.Controls.Add(btn);
}
Panel2.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.BackColor = Color.Red;
}
}