Reputation: 2000
In my application i have array of buttons created dynamically.I am trying to raise an onclick event for those buttons and change the text of the button which i click.I tried the below code for this but its not working.How can i do this?.Any suggesions?
Code:
for (int i = 0; i < 5; i++)
{
lbl = new Button[5];
lbl[i] = new Button();
lbl[i].Text = "hi";
lbl[i].Width = 30;
lbl[i].Click += new EventHandler(lbl_click);
//lbl[i].CssClass = "label";
div1.Controls.Add(lbl[i]);
}
Click Event:
protected void lbl_click(object sender, EventArgs e)
{
Button[] lbl = sender as button[];
lbl[i].Text = "clicked";
}
Upvotes: 0
Views: 6853
Reputation: 216303
You are recreating the array of buttons in your event handler, but this array is not populated with the buttons created before. It is empty and will give you a null reference exception if you try to use an element of this array (null.Text
, it will never work).
The sender object instead, represent the button that the user has clicked.
protected void lbl_click(object sender, EventArgs e)
{
Button lbl = sender as Button;
lbl.Text = "clicked";
}
Also, if you need to know which specific button has been clicked then I suggest you to add something to differentiate between them at creation time:
For example use the name property:
Button[] lbl = new Button[5];
for(int i = 0; i< 5; i++)
{
....
lbl[i].Name = "Button_" + i.ToString();
....
}
Notice that I have moved the array declaration and initialization outside the loop that create every single element of the array (the actual button).
Upvotes: 4