sunshine sunshine - 2 months ago 6
C# Question

C# How to allow my textbox.text to accept more than one digit

I am new to C#, I am trying to implement the below code, but noticed that only one digit is accepted by the textbox.text though declared as int

private void textBox1_TextChanged(object sender, EventArgs e)
{
int RegionIDInput;

if (int.TryParse(textBox1.Text, out RegionIDInput))
{
if (RegionIDInput > 254 || RegionIDInput < 1)
{
MessageBox.Show("Enter valid value");
RegionIDInput = Convert.ToInt32(textBox1.Text);
}
}
else
{
MessageBox.Show("Enter Numeric Value");
}

}

Answer

The TextChanged event is fired on every char that the user has entered, that's the reason for the issue. You can handle the Leave event:

private void textBox1_Leave(object sender, EventArgs e)
{
    int RegionIDInput;
    if (int.TryParse(textBox1.Text, out RegionIDInput))
    {
        if (RegionIDInput > 254 || RegionIDInput < 1)
        {
            MessageBox.Show("Enter valid value");
            this.ActiveControl = textBox1;
        }
    }
    else
    {
        MessageBox.Show("Enter Numeric Value");
        this.ActiveControl = textBox1;
    }
}

Note that your code converted the text twice. So i've removed the redundant RegionIDInput = Convert.ToInt32(textBox1.Text);

Comments