Recently I've notice, some smart user pass string (alphabets) in the TextBox that allow only number value (0-9) during KeyPress Event in one my projects. Unfortunately the database column type in NVARCHAR, that's why data inserting operation is completing with with invalid data. My project (Winform) is big enough to change data type of that column (NVARCHAR to INT). I got error while calculating SUM of that column in SQL Server. Here is my KeyPress Event for number only validation.
private void txtInputValue_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
}
Now how can I prevent user to stop paste some invalid data except Number (0-9). Thanks in advance for help me.
TextBox.ShortcutsEnabled = false?KeyPressEventArgs.MaskedTextBox, but still user friendly) is to let user type in anything (it should be clear what input is expected though), but validate value as it's changed (inTextChangedevent handler). Validation result can be displayed to user, so that he can correct his mistake, without restricting his input. Good example is enteringdoublevalues. Ifdouble.TryParsefails, then you can display red border or some icon to inform user what input is wrong. This approach is very good to handle special cases (blank values, constants:NaN,+Infinity, etc.).