Convert String to Int

G

Guest

I have an integer value in a textbox, i want to use the value to perform a
mathematical calculation, however i can only access this value as a string
and i can't cast a string to an int. How do i do this?
 
R

Ray Booysen

clickon said:
I have an integer value in a textbox, i want to use the value to perform a
mathematical calculation, however i can only access this value as a string
and i can't cast a string to an int. How do i do this?
(Int32)textbox1.text; for c#

Or even just use the Convert methods.

Convert.ToInt32(textbox1.text)
 
G

Guest

Ray Booysen said:
(Int32)textbox1.text; for c#

Strangely this does not work, it was the first thing i tried and i get an
error saying CS0030: Cannot convert type 'string' to 'int'. I will try the
Convert object and see how that goes.
 
K

Karl Seguin [MVP]

I wouldn't expect casting it t work. It isn't and never was an int. It's a
string with that has an integer value. Covert.ToInt32 or Int32.Parse will
work however.

Here's a function you might find handy:

public static int ParseInt(object o, int defaultValue)
{
if (o == null || o == DBNull.Value)
{
return defaultValue;
}
try
{
return Int32.Parse(o.ToString(), CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
if (!(ex is FormatException) && !(ex is InvalidCastException) && !(ex
is OverflowException))
{
throw;
}
return defaultValue;
}
}

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,184
Latest member
ZNOChrista

Latest Threads

Top