Introduzione
Il controllo **TextBox** (casella di testo) è l'elemento fondamentale per input e output testuale in Windows Forms (VB.NET) e VB6/VBA. Supporta singola riga, multiriga, sola lettura, password, maschere, validazione, completamento automatico.
Proprietà chiave
| Proprietà | Descrizione | Valori tipici |
Text | Contenuto testuale (input/output) | String |
Multiline | Consente più righe (Invio = nuova riga) | `True` / `False` (default) |
ReadOnly | Impedisce modifica utente (ma permette copia, selezione) | `True` / `False` |
PasswordChar | Carattere mascheratura (es. `*` `●`) | Char (default: nulla) |
MaxLength | Lunghezza massima caratteri (0 = illimitato) | Integer |
ScrollBars | Barre scorrimento (solo Multiline=True) | `None`, `Horizontal`, `Vertical`, `Both` |
WordWrap | Va a capo automatico (Multiline) | `True` / `False` |
AcceptsReturn | Invio inserisce nuova riga (vs attiva button default) | `True` / `False` |
AcceptsTab | Tab inserisce tabulazione (vs sposta focus) | `True` / `False` |
AutoCompleteMode | Suggerimenti durante digitazione | `None`, `Suggest`, `Append`, `SuggestAppend` |
AutoCompleteSource | Fonte suggerimenti | `FileSystem`, `HistoryList`, `CustomSource`, `AllUrl` |
CharacterCasing | Forza maiuscole/minuscole | `Normal`, `Upper`, `Lower` |
TextAlign | Allineamento orizzontale (solo SingleLine) | `Left`, `Center`, `Right` |
Modalità Input (utente digita)
Singola riga (default)
' Proprietà chiave
txtInput.Multiline = False
txtInput.MaxLength = 50
txtInput.CharacterCasing = CharacterCasing.Upper ' Forza maiuscole
' Recupero valore
Dim nome As String = txtInput.Text.Trim()
If String.IsNullOrEmpty(nome) Then
MessageBox.Show("Inserire nome.")
txtInput.Focus()
Return
End If
Multiriga (area testo)
txtNote.Multiline = True
txtNote.ScrollBars = ScrollBars.Vertical
txtNote.WordWrap = True
txtNote.AcceptsReturn = True
txtNote.AcceptsTab = True
txtNote.MaxLength = 2000
' Recupero (include vbCrLf)
Dim note As String = txtNote.Text
' Salvataggio DB: nota contiene CrLf → memorizzare come TEXT/MEMO
Password
txtPassword.PasswordChar = "●"c ' o "*"c
txtPassword.MaxLength = 20
' Nota: Text restituisce testo REALE, non mascherato
Validazione input (eventi)
' Validating: annulla se invalid (e.Cancel = True)
Private Sub txtEmail_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtEmail.Validating
If Not System.Text.RegularExpressions.Regex.IsMatch(txtEmail.Text, "^\S+@\S+\.\S+$") Then
ErrorProvider1.SetError(txtEmail, "Formato email non valido")
e.Cancel = True ' Impedisce uscita dal controllo
Else
ErrorProvider1.SetError(txtEmail, "")
End If
End Sub
' Validated: dopo validazione riuscita
Private Sub txtEmail_Validated(sender As Object, e As EventArgs) Handles txtEmail.Validated
' Es: lookup asincrono disponibilità
End Sub
Modalità Output (programma scrive)
Sola lettura (ReadOnly)
txtLog.ReadOnly = True
txtLog.BackColor = SystemColors.Window ' Bianco (default grigio se ReadOnly)
txtLog.ForeColor = Color.Black
txtLog.TabStop = False ' Escluso da navigazione Tab
' Scrittura programma
txtLog.Text = "Avvio elaborazione..." & vbCrLf
txtLog.AppendText("Step 1 completato." & vbCrLf) ' Più efficiente di Text +=
txtLog.ScrollToCaret() ' Auto-scroll alla fine
Log in tempo reale (thread-safe)
Delegate Sub AppendLogDelegate(testo As String)
Sub ScriviLogThreadSafe(msg As String)
If txtLog.InvokeRequired Then
txtLog.Invoke(New AppendLogDelegate(AddressOf ScriviLogThreadSafe), msg)
Else
txtLog.AppendText("[" & DateTime.Now.ToString("HH:mm:ss") & "] " & msg & vbCrLf)
txtLog.ScrollToCaret()
End If
End Sub
Eventi principali
| Evento | Quando scatta | Uso tipico |
TextChanged | Contenuto modificato (utente o codice) | Anteprima live, contatore caratteri, abilitazione pulsanti |
KeyPress | Tasto carattere premuto | Filtra caratteri (es. solo numeri: `If Not Char.IsDigit(e.KeyChar) Then e.Handled = True`) |
KeyDown/Up | Tasto premuto/rilasciato (tutti) | Scorciatoie (Ctrl+S), navigazione |
Enter/Leave | Focus entra/esce | Seleziona tutto all'ingresso (`txt.SelectAll()`), validazione in uscita |
MouseDoubleClick | Doppio click | Seleziona parola, apri editor esteso |
Esempio completo: Form contatti con validazione
Public Class FormContatti
Private Sub FormContatti_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Setup
txtNome.MaxLength = 50
txtEmail.MaxLength = 100
txtNote.Multiline = True
txtNote.ScrollBars = ScrollBars.Vertical
txtNote.AcceptsReturn = True
btnSalva.Enabled = False
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles txtNome.TextChanged, txtEmail.TextChanged
' Abilita salva solo se campi obbligatori pieni
btnSalva.Enabled = (txtNome.Text.Trim() <> "" AndAlso txtEmail.Text.Trim() <> "")
End Sub
Private Sub txtEmail_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtEmail.Validating
If txtEmail.Text.Trim() <> "" AndAlso Not IsValidEmail(txtEmail.Text) Then
ErrorProvider1.SetError(txtEmail, "Email non valida")
e.Cancel = True
Else
ErrorProvider1.SetError(txtEmail, "")
End If
End Sub
Private Function IsValidEmail(email As String) As Boolean
Try
Dim addr As New System.Net.Mail.MailAddress(email)
Return addr.Address = email
Catch
Return False
End Try
End Function
Private Sub btnSalva_Click(sender As Object, e As EventArgs) Handles btnSalva.Click
If Me.ValidateChildren() Then ' Forza Validating su tutti
' Salva su DB...
MessageBox.Show("Salvato: " & txtNome.Text & " - " & txtEmail.Text)
End If
End Sub
End Class
VB6 / VBA differenze
- `TextBox` in UserForm: proprietà simili (`MultiLine`, `MaxLength`, `PasswordChar`, `EnterKeyBehavior`, `TabKeyBehavior`).
- Eventi: `Change` (≈ TextChanged), `KeyPress`, `BeforeUpdate`/`AfterUpdate` (validazione), `Enter`/`Exit`.
- Validazione: `Cancel = True` in `BeforeUpdate` per annullare.
Nozioni di base sulla programmazione visuale