0
private void textBox1_TextChanged(object sender, EventArgs e)
{
    var x = textBox1.Text;
    var y = 1000000;
    var answer = x * y;
}

This is my current code. I want to take the user input from textBox1 and multiply it by 1000000 because it needs to convert the user input. But This code doesn't because x technically isn't a numerical value. How would I get this functioning?

kaveman
  • 4,339
  • 25
  • 44
Justin Dosaj
  • 61
  • 10
  • 1
    `textbox1.;` is a syntax error. Did you mean `textbox1.Text;`? – kaveman Jun 30 '15 at 17:13
  • 1
    You're looking for this: [How can I convert String to Int?](http://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) – cbr Jun 30 '15 at 17:15
  • You might want to have a look at this quistion/answer: [Get integer from textbox](http://stackoverflow.com/questions/11931770/get-integer-from-textbox) – Rednax Jun 30 '15 at 17:15

3 Answers3

3

This is getting text, not a number:

var x = textBox1.Text;

Since C# is statically typed, you need to explicitly turn it into a number. For this you can use something like int.TryParse(). For example:

var xText = textBox1.Text;
var x = 0;
if (!int.TryParse(xText, out x))
{
    // display an error to the user
    return;
}
var y = 1000000;
var answer = x * y;

That way you're testing if the text input can be parsed as a number and, if it can't, displaying a message to the user. Rather than assuming the input and getting an unhandled exception.

There are also TryParse() methods for other numeric types, in case you want to use something like a double or a float for other calculations.

David
  • 208,112
  • 36
  • 198
  • 279
2

You can use Int32.Parse if you're sure user input is a number or int.TryParse if you need to validate it.

I'm assuming integer inputs only what could be wrong though. Same applies for other numeric types. (they all have Parse and TryParse)

Using Int32.Parse

private void textBox1_TextChanged(object sender, EventArgs e)
{
     var x = Int32.Parse(textBox1.Text); // you're sure text is numeric
     var y = 1000000;
     var answer = x * y;
}

Using Int32.TryParse

private void textBox1_TextChanged(object sender, EventArgs e)
{
     int x = 0;
     if (Int32.TryParse(textBox1.Text, out x)) // you're NOT sure if text is numeric
     {
          var y = 1000000;
          var answer = x * y;
     }
     else 
     {
          // let the user know that numeric values are required
     }
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
-4

This will get you your numerical values

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            float x = Float.Parse(textBox1.text, CultureInfo.InvariantCulture);
            float y = 1000000;
            float answer = x * y;
        }
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37