简体   繁体   中英

Issue in converting string to integer

I want to use CalcEngine library for doing math calculations in multiple textboxes. This code is a part of the whole project. Why is it give error? The error is in "CE.Evaluate(textBoxTLA.Text).ToString()" part

private void button1_Click(object sender, EventArgs e)
    {
        CalcEngine.CalcEngine CE = new CalcEngine.CalcEngine();
        int.TryParse(textBoxTLA.Text, CE.Evaluate(textBoxTLA.Text).ToString());

    }

TryParse takes an integer as a second parameter, and you are supplying a String .

It works like this (I don't know which string you want parsed, I assumed the evaluated one):

int target;
CalcEngine.CalcEngine CE = new CalcEngine.CalcEngine();
int.TryParse(CE.Evaluate(textBoxTLA.Text).ToString(), out target);

It is better to use Parse though, so you can do correct error handling (plus the code will be more readable).

Also, you are doing a lot in one line, which makes it harder to debug, and to give clear messages to your user. For example, what if CE.Evaluate fails?

TryParse recieves two parameters, the string you want to parse, and an out parameter that receives the output..

So say my string is textBoxTLA.Text , I would parse it to int like this:

int myInt;
if(int.TryParse(textBoxTLA.Text, out myInt))
{
//Do whatever you need with calcEngine
}

It does this so it can return a bool value of whether or not it succeeded, so if you don't enter the if cause it was not able to parse the int. Make sure to use this and avoid errors and exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM