Italian Crazione di bottoni o altro a runtime e reperimento degli eventi...

Gennaro Frungillo

Member
Licensed User
Longtime User
Salve a tutti,
vi spiego in VB.NET quello che vorrei ottenre in B4A con un semplice codice:
B4X:
For i = 1 to 10
   dim btn as new Button
   btn.Text = i
   btn.Name = "btn_" & i
   Panel1.Controls.Add(btn)
   AddHandler btn.Click, Addess Of ClickBottoni
next

Private Sub ClickBottoni(sender as Object, e as EventArgs)
   dim btn as Button = Sender
   msgBox("Hai Cliccato il Bottone:" & btn.text
end Sub

Ora, partendo dal fatto che in B4A sono riuscito a fare fino a qui :
B4X:
Dim top As Int = 5
    Dim left As Int = 5
    For i = 1 To 15
        Dim btn As Button
        btn.Initialize("bottone")
        btn.Text = i
        Panel1.AddView(btn,left,top,100,100)
        top = top + 100
        If i = 5 OR i = 10 Then
            top = 5
            left = left + 100
        End If
       
    Next
...e funziona egregiamente, il problema è quando vado a dichiarare la Sub "bottone"; se provo a mettere il parametro "sender as object" il compilatore si incazza.
La domanda è:
Dopo aver generato i bottoni a RunTime come posso gestirne gli eventi dei singoli bottoni senza dovere dichiarare n eventi per n bottoni?


Grazie a tutti!
 

LucaMs

Expert
Licensed User
Longtime User


Se metti:

B4X:
Sub bottone_Click
    Dim btn As Button
    btn = Sender
    Msgbox("hai premuto " & btn.Text, "")
End Sub

dovrebbe tranquilizzarsi
 

AlpVir

Well-Known Member
Licensed User
Longtime User
Se poi sfrutti la proprietà tag di ciascun pulsante sei in grado, nella sub bottone_click, di distinguere ogni pulsante.
Qualcosa del genere (nella parte in cui crei i pulsanti)
btn.tag = i
e
if btn.tag = 1 then ...
if btn.tag = 2 then ...

Nota che nella sub bottone_click ha definito
Dim btn as Button
ma avresti benissimo potuto scrivere
Dim botto as Button
Nel qual caso ovviamente bisogna scrivere
botto = Sender
 

Gennaro Frungillo

Member
Licensed User
Longtime User
Se metti:

B4X:
Sub bottone_Click
    Dim btn As Button
    btn = Sender
    Msgbox("hai premuto " & btn.Text, "")
End Sub

dovrebbe tranquilizzarsi
Grazie, non sapevo che sender era globale

Nota che nella sub bottone_click ha definito
Dim btn as Button
ma avresti benissimo potuto scrivere
Dim botto as Button
Nel qual caso ovviamente bisogna scrivere
botto = Sender
Certo!!! Grazie!
 

Claudio57

Member
Licensed User
Longtime User
In questo caso non è necessario mettere il tag perché basta controllare il text del bottone per sapere qual è. Giusto?
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…