Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can we identify a button whether it is clicked or not,when those buttons are created as dynamic button array?

Question
there are set of buttons in a column which are created from a for loop(dynamically).
2nd button of the column is clicked.how can we identify that the user has clicked the 2nd button?
{
 x = 30;
 for (int i = 0; i < ar.Length; i++)
 {
     bu[index1] = new Button();
     bu[index1].Location = new Point(50, x);
     bu[index1].Size = new Size(75, 20);
     bu[index1].Text = "1";
     bu[index1].Name = b+ i;
     bu[index1].Click += new EventHandler(button_Click1);
     x = x + 100;
     index1++;
 }
 this.Controls.AddRange(bu);
}

private void button_Click1(object sender, EventArgs e)
{
     if(bu[0].Name=="b0")
     MessageBox.Show("selected rw1");
     else if(bu[1].Name=="b1")
     MessageBox.Show("selected rw2";

}

above code is not working expected as explained in the Question.can any one help me to correct this??
Posted

You have the sender argument available, use it. For instance:

C#
private void button_Click1(object sender, EventArgs e)
{
  Button selected = sender as Button;
  MessageBox( selected.Name);
}
 
Share this answer
 
Comments
Olivier Levrey 24-Mar-11 9:06am    
My 5.
Member 7779792 24-Mar-11 10:36am    
thanx alot!appreciate your help very much!thnx once again.
bu[index1].Name = "b" + i;
Don't forget the quotes! (Your compiler should be picking that mistake up though unless you happen to have a string or numeric variable called b lying around.)

In the handler you need to be checking the name of the button that was actually clicked ((Button)sender). If bu is a global array you could also look for sender in bu in the handler to discover the index of the button that was clicked.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900