uzi42tmp
uzi42tmp

Reputation: 291

TextBox accepts only int

I have a problem with my textbox. I wanted that one can manually set the interval of the x- and y-axis for a chart in the GUI over two textboxes. That works but when I type a char in or when I typed an int in and delete it, the program crashes immediately and I get a System.FormatException (without clicking the button to accept the changes). How can I solve it that one can just type in different signs without immediately crashing the program? My code below:

public void textBox2_TextChanged(object sender, EventArgs e)
{
     x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);
}

private void yAxisBox_TextChanged(object sender, EventArgs e)
{
    y_axis_num = Convert.ToInt32(yAxisBox.Text);
} 

That gets passed to another event:

chart1.ChartAreas[0].AxisX.Interval = x_axis_num;
chart1.ChartAreas[0].AxisY.Interval = y_axis_num;

Upvotes: 0

Views: 192

Answers (1)

Nahuel Ianni
Nahuel Ianni

Reputation: 3185

In the line x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);, you are taking whatever is in the text box and try to convert it to an integer value.

What do you think the conversion of "Hey, I'm not a number!" will do? It will crash horribly, basically because that text is not, and never will be, a number.

Instead, you can use the Int.TryParse method which will take any text and TRY to convert it to a number.

If the conversion is successful, then no problem. If it was not successful, then you get a false value on a flag indicating the text could not be converted.

Example:

int number;

bool result = Int32.TryParse(YourTextBox.Text, out number);

If the conversion is successful, then number has the value, otherwise, result is false so do something like this then:

if(result)
{
    xAxisBox.Text = number.ToString();
    x_axis_num = number;
}
else
{
    xAxisBox.Text = string.Empty;

    // Be careful here with what you set. 
    // This is the value you will set when the Text box has a non numeric value!
    x_axis_num = 0;    
}

Upvotes: 3

Related Questions