Is there a way to only allow a user to input a maximum number of characters into a text box? I want the user to input a mark/grade and only be able to input 0 - 100. Below I have code that monitors the keystroke and only allows for numbers to be input, but I want to find a way to only allow the user to input a number with a minimum value of 0 and a maximum of 100.
private void TxtMark4_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0' || e.KeyChar > '9' || e.KeyChar == ' ')
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
or I could use the following:
if (e.KeyChar >= 48 && e.KeyChar <= 57 || e.KeyChar == ' ')
{
e.Handled = false;
}
else
{
MessageBox.Show("You Can Only Enter A Number!");
e.Handled = true;
}
But I would like to find a way to only allow three characters to be input maximum.
This version set textBox1.Text to empty string if fail to parse
If you want to keep the partial successfully parsed number then
I would do it like this with catch for every possible user error.
I'm assuming you textbox is named TxtMark4. Write txtMark4.Content() or what ever you need to read the content of the textbox in your framework in the if-test which does the TryParse
I think it is as simple as:
Then you handle the maximum value on the Leave event:
or
You could also use System.Windows.Forms.NumericUpDown where you can easily setup minimum and maximum.