Home > Blockchain >  How to convert textbox to int in c#
How to convert textbox to int in c#

Time:05-22

I put in textbox=1 and I want to add one to it like this:

Textbox.text =1;

But not add it apear (11) I want to apear (2)

CodePudding user response:

You need to convert it to int then add 1 to it.

int temp_ans = Convert.ToInt32(Textbox.text)   1;
Textbox.text = temp_ans.ToString();

CodePudding user response:

I want to expand a little on Darth-CodeX answer.

Your Textbox is a type String (Text). The operation you are trying to do (adding 1) is for numeric types only.
When using = on a text, it will try to autoconvert the input to Text 1 (number) -> "1" (text). The example you showed is to add (append) letters to the existing string (text) example:

Textbox.Text  = "Apples";
Textbox.Text  = " are ";
Textbox.Text  = " awesome!";

In order to process the number in a mathematical way, you need to convert the text to a number first:

int conversion = int.Parse(Textbox.Text); // convert to int (1,2,3,4,...)
// double conversionWihDecimal places; // convert to double (1.213221)
conversion  = 1; // add 1 to conversion
Textbox.Text = conversion.ToString(); // convert back and update textbox

Note that your application will crash if you try to parse the Text "Apple" to a number for example. You can either add checking functions or use int.TryParse(). I use double in the example below as it will cover decimal positions (123.321) as well. Additionally, I use .Trim() to remove any whitespaces at the start and end of text.

double conversion;
if (double.TryParse(Textbox.Text.Trim(), out conversion)
{
    conversion  = 1; // add 1 to conversion
    Textbox.Text = conversion.ToString(); // convert back and update textbox
}

CodePudding user response:

int answer = Convert.ToInt32(Textbox.text);
 answer = 1;
  •  Tags:  
  • c#
  • Related