TextBox limitare l'inserimento di alcuni carratteri

giovedì 10 aprile 2008 - 20.03

jtpsala Profilo | Senior Member

Saluto tutti gli utenti di questo Forum.
Ho una domanda da porVi:
nell'evento KeyPress di una textbox come posso fare in modo che l'utente non digiti caratteri speciali (!"£$%&/()=?^*駰_-.:,;<>€\|)?
Qualcuna mi saprebbe indicare il codice da utilizzare?
Ringrazio tutti in anticipo.

aiedail92 Profilo | Expert

Ciao

Potresti controllare la proprietà KeyChar di e, e se è uno dei caratteri che non vuoi siano immessi, impostare la proprietà Handled di e a true:

private void tuaTextBox_KeyPress(object sender, KeyPressEventArgs e) { List<char> unacceptedChars = new List<char> (new char[] { '!', '"', '£', ', '%', '&', ecc }); if (unacceptedChars.Contains(e.KeyChar)) { e.Handled = true; } }

Naturalmente puoi dichiarare unacceptedChars nella classe così da non doverlo reistanziare tutte le volte.

Luca

TOPOAMORE Profilo | Expert

ciao

prova nell'evento keypress

If Not (Char.IsSimbol(e.KeyChar)) and (Char.isPunctuation(e.KeyChar)) Then e.Handled = True End If

fammi sapere ciaoo

jtpsala Profilo | Senior Member

Grazie TOPOAMORE, sei sempre grande.
Avevo risolto con questo codice per poter inserire nella textbox solamente numeri:

If (e.KeyChar > Chr(47) And e.KeyChar < Chr(58)) Or e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True End If
Invece, per far digitare nella textbox solo lettere maiscole:

If (e.KeyChar > Chr(64) And e.KeyChar < Chr(122)) Or e.KeyChar = Chr(8) Then e.Handled = False End If

e ovviamente per sole quelle minuscole:

If (e.KeyChar > Chr(96) And e.KeyChar < Chr(122)) Or e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True End If

Il problema è che non riesco nella textbox far digitare sia le lettere maiuscole, sia le minuscole. Probabilmente "canno" quelche passaggio?

TOPOAMORE Profilo | Expert

in pratica vuoi solo lettere?

jtpsala Profilo | Senior Member

Si, solo maiuscole e minuscole.
Io sto utilizzando questo codice:

'non accettare carratteri speciali If Not (Char.IsSymbol(e.KeyChar)) And (Char.IsPunctuation(e.KeyChar)) Then e.Handled = True End If 'accettare solo lettere If (Char.IsNumber(e.KeyChar)) Then e.Handled = True End If

Può andar bene?

aiedail92 Profilo | Expert

In questo caso potresti usare Char.IsLetter:

If Not Char.IsLetter(e.KeyChar) Then e.Handled = True End If

E se vuoi poter immettere anche gli spazi:

If Not (Char.IsLetter(e.KeyChar) Or _ Char.IsWhiteSpace(e.KeyChar)) Then e.Handled = True End If

Luca

jtpsala Profilo | Senior Member

Ringrazio per la risposta.
Ciao.
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?

Dopo esserti registrato potrai chiedere
aiuto sul nostro Forum oppure aiutare gli altri

Consulta le Stanze disponibili.

Registrati ora !
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5