2010-01-20 5 views

risposta

29

Provate il seguente

Button b1 = CreateMyButton(); 
b1.Click += new EventHandler(this.MyButtonHandler); 
... 
void MyButtonHandler(object sender, EventArgs e) { 
    ... 
} 
+1

grazie, ma in realtà non si adatta alle mie esigenze. Ho provato a cercare sul web in base a ciò che mi hai dato, ma non sono riuscito a trovare o capire nulla. Il risultato è che ho una serie di pulsanti. E mi piacerebbe sapere quale pulsante è stato cliccato. – jello

+0

@jello, hai mai trovato la soluzione per capire quale pulsante è stato premuto? Ho un problema simile adesso. – mdw7326

2

sembra come questo funziona, mentre l'aggiunta di un tag con ogni elemento della matrice

Button button = sender as Button; 

Sei a conoscenza di un modo migliore?

3

Se si desidera visualizzare il pulsante su cui è stato fatto clic, è possibile effettuare le seguenti operazioni dopo aver creato e assegnato i pulsanti. Considerando che si creano gli ID dei pulsanti manualmente:

protected void btn_click(object sender, EventArgs e) { 
    Button btn = (Button)sender // if you're sure that the sender is button, 
           // otherwise check if it is null 
    if(btn.ID == "blablabla") 
     // then do whatever you want 
} 

è anche possibile controllare loro di dare un argomento di comando a ogni pulsante.

19

Usa questo codice per gestire diversi pulsanti fare clic su Eventi:

private int counter=0; 

    private void CreateButton_Click(object sender, EventArgs e) 
    { 
     //Create new button. 
     Button button = new Button(); 

     //Set name for a button to recognize it later. 
     button.Name = "Butt"+counter; 

     // you can added other attribute here. 
     button.Text = "New"; 
     button.Location = new Point(70,70); 
     button.Size = new Size(100, 100); 

     // Increase counter for adding new button later. 
     counter++; 

     // add click event to the button. 
     button.Click += new EventHandler(NewButton_Click); 
    } 

    // In event method. 
    private void NewButton_Click(object sender, EventArgs e) 
    { 
     Button btn = (Button) sender; 

     for (int i = 0; i < counter; i++) 
     { 
      if (btn.Name == ("Butt" + i)) 
      { 
       // When find specific button do what do you want. 
       //Then exit from loop by break. 
       break; 
      } 
     } 
    } 
0

In merito al suo commento dicendo vuoi sapere quale pulsante è stato cliccato, è possibile impostare l'attributo .Tag di un pulsante per qualsiasi tipo di stringa di identificazione che si desidera come è stato creato e utilizzare

private void MyButtonHandler(object sender, EventArgs e) 
    { 
     string buttonClicked = (sender as Button).Tag; 
    } 
+0

Almeno questo è il modo più semplice a cui possa pensare. – TehSpowage