Convert textbox text to int - Error even after TryParse()

1k views Asked by At

What should (hopefully) be a simple problem...

I have a function called updateChart(), where the program takes a value input from a textbox (txtBP), and tries to convert it into an integer to be stored in a local variable (latestReading) and used as a graph coordinate.

I originally tried to do this like this:

int latestReading = Convert.ToInt32(txtBP.Text);

This caused a run-time error informing me that "Input string was not in the correct format". After some research I have learned that to convert text from a textbox to an int, you should use the TryParse method. I tried this method out as such:

int x = 0;
int latestReading = 0;

if (Int32.TryParse(txtBP.Text, out x))
{
    latestReading = Convert.ToInt32(txtBP.Text);
}
else
{
    MessageBox.Show("Invalid Reading!");
}

I was sure this would work, but when it came to testing, even entering the the value 1 into the textbox myself caused it to jump to the 'else' part of the statement. I have read around on stack overflow but can't find a similar situation.

1

There are 1 answers

0
marcuthh On BEST ANSWER

Just to let everyone know, I got the thing working.

Calling the updateChart() function on the button click seemed to be throwing it off, by calling it inside a function that was already called on the button click, it seems to be able to access the data from the textbox. Still not entirely sure how this happens but no complaining.

Thank you to you all for your help!

Mark