Mallory Rich Mallory Rich - 2 months ago 19
C# Question

Windows Form. Limit User input to a certain range

I am creating a windows form program for class and I am trying to limit input for a 'weight' textbox from 1-1000. I got the user input to parse to a double but some reason the error message I created will not popup at the right time as intended. (The error message will popup only if I enter digits passed 5 digits... so I can enter 2222 or 10000 without an error)

private void Weight_KeyPress(object sender, KeyPressEventArgs e)
{
var sourceValue = Weight.Text;
double doubleValue;
if (double.TryParse(sourceValue, out doubleValue))
{
if (doubleValue > 1000 )
{
MessageBox.Show("Cannot be greater than 1000");
}
}
}

Answer

instead of using KeyPress you should use TextChanged event because if you use keypress the new char is not part of the control text yet.

private void inputTextBox_TextChanged(object sender, EventArgs e)
        {
            var inputTextBox = sender as TextBox;
            var sourceValue = inputTextBox.Text;
            double doubleValue;
            if (double.TryParse(sourceValue, out doubleValue))
            {
                if (doubleValue > 1000)
                {
                    MessageBox.Show("Cannot be greater than 1000");
                }
            }
        }
Comments