Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

WinForms TextBox to accept numbers in a range

4.00/5 (1 vote)
10 Jan 2012CPOL 10K  
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
C#
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).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)