-5

to convert int to string in text field ( visual studio)

int id = int.parse(textfield1.Text).ToString();

it makes error please do solve this ?

Essam Fahmi
  • 1,920
  • 24
  • 31
  • 4
    Please read the error, it says what you did wrong. That's the purpose of error and it's messages. – Renatas M. Aug 08 '17 at 08:00
  • `ToString()` converts an object type to a string type. Why would need it to map the value to an `int` type? – praty Aug 08 '17 at 08:06
  • 1
    Possible duplicate of [How can I convert String to Int?](https://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) – Essam Fahmi Aug 08 '17 at 08:14

5 Answers5

3

You don't need To.String on the end.

Just

int id = int.Parse(textfield1.Text);
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
1

the first try that may come to your mind is to do:

var id = textfield1.Text;
Console.WriteLine(id);

or

var id = int.Parse(textfield1.Text);

but that is not safe at all (what if textfield1 is holding something that can not be converted into an integer?)

that is why the best way you take should be.

//here the result of the conversion
var output = -1;
// a variable to verify whether the result was ok or not.
var resultOk = Int32.TryParse(textfield1.Text, out output);  

Console.WriteLine(output );
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • no need to assign `output`, however. `TryParse` will do that for you (out params are guaranteed to be assigned). – Rufus L Aug 08 '17 at 08:33
0

you have a typo parse should be Parse =>int.Parse and you don't need the tostring after that because you are converting it back to string

 int id = int.Parse(textfield1.Text);
npo
  • 1,060
  • 8
  • 9
0

You are converting it back to string again when calling .ToString() just use

int id = int.parse(textfield1.Text);

or this to avoid invalid values

int id;
if(int.TryParse(textfield1.Text,out id)){
  //Valid value
}
else
{
  //Invalid value
}
0

To convert int to string, you can use one of following methods :

1.

int number = 0;
string value = "5";

number = int.parse(value);
// your code

or 2.

int number = 0;
string value = "5";

number = Convert.ToInt32(value);
// your code

or 3.

int number = 0;
string value = "5";

bool result = Int32.TryParse(value, out number); 
if (result == true)
{
    // your code
}
Essam Fahmi
  • 1,920
  • 24
  • 31