WinForms TextBox to accept numbers in a range





4.00/5 (1 vote)
I will use a label with font color red just below the text box and will adopt the following code private void textBox1_TextChanged(object sender, EventArgs e) { int min=0,max=256; try { label1.Visible = false; ...
I will use a label with font color red just below the text box and will adopt the following code
private void textBox1_TextChanged(object sender, EventArgs e)
{
int min=0,max=256;
try
{
label1.Visible = false;
int n = int.Parse(textBox1.Text);
if (n > max || n < min)
{
label1.Text="Number can be only in range "+min.ToString()+" and "+max.ToString();
label1.Visible = true;
// textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
catch (Exception ex)
{
label1.Text = "Not a Number";
label1.Visible=true;
//textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
If you un-comment the comment lines, it will remove the last character, though label will not be visible(Also there is a small bug, the cursor will go to first position which can be set to last character).