I am trying to learn C# etc by making this code work, its a mix of examples I've found on the web. The problem is the event handler never triggers. I would also like to change the text of the button that was clicked in the event handler. In a nutshell, I want to create an array of buttons, then change attributes as the text or color of the button selected. Eventually I want to add an array of labels which correstpond to these buttons and change the text or color depending on which button is pushed. Any help is appreciated.
public partial class _Default : System.Web.UI.Page{ static Button[] btn_arr = new Button[14]; static int btn_count;
protected void Page_Load(object sender, EventArgs e) { try { if (btn_arr[0] is Button) { foreach (Button button in btn_arr) { add_button(button); } } else {
for (int i = 0; i < 14; i++) { Button new_button = new Button(); new_button.ID = "btn" + Convert.ToString(i); new_button.Text = "Button" + Convert.ToString(i); new_button.Click += new EventHandler(btn_Click); btn_arr[btn_count++] = new_button; add_button(new_button); } } } catch (Exception ex) { lblStatus.Text += ex.Message.ToString(); } }
protected void add_button(Button button) { try { panelLineA.Controls.Add(button); } catch (Exception ex) { lblStatus.Text += ex.Message.ToString(); } }
// this is never triggered void btn_Click(object sender, EventArgs e) { int btnIndex = Convert.ToInt32(((Button)sender).ID.Substring(3, 1)); lblStatus.Text = "Button " + btnIndex + " was pushed." + ((Button)sender).ID;
}