I have a TextBoxD1.Text
and I want to convert it to an int
to store it in a database.
How can I do this?
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
}
You can convert a string to int in C# using:
Functions of convert class i.e. Convert.ToInt16()
, Convert.ToInt32()
, Convert.ToInt64()
or by using Parse
and TryParse
Functions. Examples are given here.
You can convert string to int many different type methods in C#
First one is mostly use :
string test = "123";
int x = Convert.ToInt16(test);
if int value is higher you should use int32 type.
Second one:
int x = int.Parse(text);
if you want to error check, you can use TryParse method. In below I add nullable type;
int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);
Enjoy your codes....
This code works for me in Visual Studio 2010:
int someValue = Convert.ToInt32(TextBoxD1.Text);
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 Int32.TryParse Method (String, Int32) for more detailed information.
You can do like below without TryParse or inbuilt functions:
static int convertToInt(string a)
{
int x = 0;
for (int i = 0; i < a.Length; i++)
{
int temp = a[i] - '0';
if (temp != 0)
{
x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
}
}
return x;
}