tags:

views:

701

answers:

9

I have

TextBoxD1.Text

and I want to convert it to 'int' to store it in a database. How can I do this?

+2  A: 

Convert.ToInt32( TextBoxD1.Text )

Babak Naffas
+23  A: 

Try this:

int x = Int32.Parse(TextBoxD1.Text);

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Also, since Int32.TryParse returns a bool you can its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

If you are curious, the difference between Parse and TryParse is best summed up like this:

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - MSDN

Andrew Hare
+4  A: 

int.TryParse It won't throw if the text is not numeric

n8wrl
This is better than the other two. User input is likely to be the wrong format. This one is more efficient than using exception handling like the others require.
UncleO
Exactly. It returns false if the conversion failed.
n8wrl
+3  A: 

You need to parse the string, and you also need to ensure that it is truly in the format of an integer.

The easiest way is this:

int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
   // Code for if the string was valid
}
else
{
   // Code for if the string was invalid
}
Jacob
+2  A: 
int myInt = int.Parse(TextBoxD1.Text)

another way would be

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

The difference between the two is that the first one would throw an exception if the value in your textbox can't convertet, where as the second one would just return false

Andre Kraemer
+1  A: 

As explained in the TryParse documentation, TryParse() returns a boolean which indicates that a valid number was found:

bool success = Int32.TryParse(TextBoxD1.Text, out val);

if (success)
{
// put val in database
}
else
{
// handle the case that the string doesn't contain a valid number
}
JeffH
+2  A: 
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

the TryParse statement returns a boolean representing whether the parse has succeeded or not. If it succeeded, the parsed value is stored into the second parameter.

see here for more detailed info.

jorelli
A: 

It appears the TryParse method throws an exception when the object to be converted is nothing; I could be mistaken.

Alex
A: 

int i;

i=Convert.ToInt32(TextBoxD1.Text.ToString());

deepu