Share via


Hot do I set the MaskedTextBox to only allow numbers between 0-60?

Question

Monday, May 3, 2010 7:48 PM

I have a MaskedTextBox on a FORM that needs to limit the user from entering string values or any negative number value or a value over 60 (between 0-60).

I have set the Mask to "00" which restricts the user input to number values...  I also tried to put a small peace of code to evaluate for the number vale but it fails to execute.

  private void txtLatDeg_TextChanged(object sender, EventArgs e)
    {
      if (Convert.ToInt32(this.txtLatMin.Text) >= 60 || this.txtLatMin.Text.Length >= 3)
      {
        MessageBox.Show("You have entered an invalid number for the Minutes. ( Must be between 0 & 60).", "YachtLog3", MessageBoxButtons.OK, MessageBoxIcon.Information);
        this.txtLatDeg.Text = "";
      }
    }

As you can see from the above code I tried to limit the range but it fails.  I have been told that I should be using the KeyPress event to evaluate every char that the user presses.  Not sure how, does anyone have an example of a KeyPress event?Phill

All replies (6)

Tuesday, May 4, 2010 9:44 AM âś…Answered

private void txtLatDeg_Validating(object sender, CancelEventArgs e)
{
 e.Cancel = int.Parse(txtLatDeg.Text) >= 60;
}

Monday, May 3, 2010 10:38 PM

Your code is looping on the value being set to nothing.


Monday, May 3, 2010 10:43 PM

//create a stand alone Event handler Global var
 EventHandler eh = new EventHandler(tb_XXX_TextChanged);

//At load time add this 
 tb_XXX.TextChanged += eh;

//At text changed time remove it...
 tb_XXX.TextChanged -= eh;

//do your reset of the text area to clear the value
tb_xxx.Text = "";

//add the event hander
 tb_XXX.TextChanged += eh;

Javaman


Tuesday, May 4, 2010 4:32 AM

 

Better to use a numericupdown control instead of masked textbox.

-Amit


Tuesday, May 4, 2010 10:28 AM

private void mtbox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            if (char.IsNumber (e.KeyChar))

            {

                string str = mtbox1.Text + e.KeyChar;

                if (Convert.ToInt32(str) > 60)

                       e.Handled = true;

                            

              

            }

             else if (!(e.KeyChar  == (char)Keys .Back ))

                e.Handled = true;

            

        }


Tuesday, May 4, 2010 1:40 PM

Louis, that's a great trick, thanks for posting that...Javaman