
Prendendo spunto dal gioco della tombola, l’esercitazione ha lo scopo di:
- definire una funzione che restituisce un valore al codice chiamante tramite l’istruzione Return;
- utilizzare la classe Random per la generazione di numeri pseudo-casuali;
- generare una scansione dei controlli presenti nel form (Me.Controls) attraverso il costrutto For Each … Next per evidenziare le caselle corrispondenti ai numeri estratti.
Public Class frm_Tombola
Dim NumeriEstratti(90) As Short
Private Sub btn_EstraiNUmero_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_EstraiNUmero.Click
Dim NomeCasella As String
lbl_NumeroEstratto.Text = NumeroEstratto()
NomeCasella = "txt_Numero" & lbl_NumeroEstratto.Text
Dim CasellaEstratta As Control
For Each CasellaEstratta In Me.Controls
If CasellaEstratta.Name = NomeCasella Then
CasellaEstratta.BackColor = Color.PaleVioletRed
CasellaEstratta.ForeColor = Color.Wheat
Exit For
End If
Next
End Sub
Private Function NumeroEstratto() As Short
Dim Casuale As New Random
Dim Beccato As Boolean = False
NumeroEstratto = 0
While Beccato = False
NumeroEstratto = Casuale.Next(1, 91)
If NumeroEstratto = NumeriEstratti(NumeroEstratto - 1) Then
Beccato = False
Else
Beccato = True
NumeriEstratti(NumeroEstratto - 1) = NumeroEstratto
End If
End While
Return NumeroEstratto
End Function
End Class
Le 90 TextBox potevano essere implementate anche da codice mediante la seguente routine:
Public Sub CostruisciTabellone()
Dim PosX As Short = 20, PosY As Short = 20
Dim TipoCarattere As New Font("Verdana", "12")
Dim Riga, Colonna As Integer
For Riga = 1 To 9
For Colonna = 1 To 10
Dim Casella As New TextBox
With Casella
.Font = TipoCarattere
.BackColor = Color.WhiteSmoke
.ForeColor = Color.Gray
.Name = "txt_Numero" & (Riga - 1) & Colonna
.Width = 45
.Left = PosX + .Width * (Colonna - 1)
.Top = PosY + .Height * (Riga - 1)
.Text = (Riga - 1) * 10 + Colonna
.Visible = True
.TextAlign = HorizontalAlignment.Center
.ReadOnly = True
.TabStop = False
End With
Me.Controls.Add(Casella)
Next
Next
End Sub