How do i convert string to int?

  • Thread starter Thread starter Patrik Malmström
  • Start date Start date
Is there an advantage of using this over, say, Int32.Parse(string) or is it
just a matter of preferance?

Convert.ToInt32 checks to see if string is null (returns 0 if true) ,
then calls Int32.Parse
 
But it doesn't return zero for an EMPTY string, like from a textbox.
For intstance...
Convert.ToInt32(textBox1.Text).ToString()
// rets emptystring if empty
Zeke
 
But it doesn't return zero for an EMPTY string, like from a textbox.
For intstance...
Convert.ToInt32(textBox1.Text).ToString()
// rets emptystring if empty

Yep. You'll just have to do it like this:
if (textBox1.Text.ToString().Length==0)
//assign 0 to whatever
else //call convert
 
Austin Ehlers said:
Yep. You'll just have to do it like this:
if (textBox1.Text.ToString().Length==0)
//assign 0 to whatever
else //call convert
Austin,
I've been looking for a way, in these cases, to eliminate
an "if", *and* the use of:
int x = Convert.ToInt32(
(textBox1.Text == "" ? "0" : textBox1.Text));
It's long and tedious coding but it woiks. The compiler
(or control) s/b smarter than that.
Matt
 
Try: int x = int.Parse("0" + textBox1.Text);

Simple.

-Noah Coad
MS MVP & MCP [.NET/C#]
 
Back
Top