In questo post vedremo come creare una TextBox personalizzata che accetti in input solo caratteri di tipo numerico, completamente riutilizzabile.
Procediamo aggiungendo al nostro progetto una nuova classe di nome "NumericTextBox" e facendo in modo che erediti dalla classe TextBox:
namespace CustomControl
{
public class NumericTextBox : TextBox
{ }
}
Inseriamo una property di tipo bool che indicherà se sono permessi o meno numeri negativi:
public bool AllowNegative { get; set; }
Ora nel costruttore della nostra classe intercettiamo l'evento KeyPress:
public NumericTextBox()
{
this.KeyPress += new KeyPressEventHandler(NumericTextBox_KeyPress);
}
Infine andiamo ad implementare il metodo NumericTextBox_KeyPress, nel quale grazie alla classe NumberFormatInfo andremo a discriminare i caratteri del separatore decimale e dei segni positivo/negativo della cultura correntemente impostata:
void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
string decimalSeparator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
string negativeSign = NumberFormatInfo.CurrentInfo.NegativeSign;
string positiveSign = NumberFormatInfo.CurrentInfo.PositiveSign;
//se è un carattere di tipo controllo
if (char.IsControl(e.KeyChar))
return;
//se è il segno negativo
else if (AllowNegative && e.KeyChar.ToString() == negativeSign && ((TextBox)sender).Text == string.Empty)
return;
//se è il segno positivo
else if (e.KeyChar.ToString() == positiveSign && ((TextBox)sender).Text == string.Empty)
return;
//se è il carattere di separatore decimale e questo non è già presente
else if (e.KeyChar.ToString() == decimalSeparator && !((TextBox)sender).Text.Contains(decimalSeparator))
return;
/ / if it is a numeric character
else if (char.IsNumber (e.KeyChar))
return;
/ / in all other cases else
e.Handled = true;}
A You can now enter our NumeriTextBox in the toolbar and drag it to the form as a normal control:
Selecting NumericTextBox, the tab of the properties will be possible to exploit the property AllowNegative previously inserted to allow whether to place a negative number: