locked
Convert RRS feed

  • Question

  • I'm very new to c#, and want to be able to take a string from a textbox, convert it to int, do some calculations with it, then convert it back to string.

    Presuming A is the string value and b is the int value, what piece of code would perform the conversion, and then back again.

    thanks

    Saturday, April 1, 2006 10:42 AM

Answers

  • On top of what Greg has stated, if there is a chance that the TextBox contains text that isn't a number (which if users are entering it, more than likely), then use the int.TryParse method:



    int value;
    if (!int.TryParse(textbox1.Text, out value))
    {
        MessageBox.Show("Please enter a valid number.");
        return;
    }
    value = value * 2;
    textbox1.Text = value.ToString();

     

    Saturday, April 1, 2006 8:38 PM

All replies

  • string a = Textbox.Text;
    int b = int.Parse(a);
    b = b * 2 + 7;
    Textbox.Text = b.ToString();

     

    Cheers,

    Greg

    Saturday, April 1, 2006 11:51 AM
  • On top of what Greg has stated, if there is a chance that the TextBox contains text that isn't a number (which if users are entering it, more than likely), then use the int.TryParse method:



    int value;
    if (!int.TryParse(textbox1.Text, out value))
    {
        MessageBox.Show("Please enter a valid number.");
        return;
    }
    value = value * 2;
    textbox1.Text = value.ToString();

     

    Saturday, April 1, 2006 8:38 PM