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?
Be careful when using Convert.ToInt32()
on a char!
It will return the UTF-16 code of the character!
If you access the string only in a certain position using the [i]
indexing operator, it will return a char
and not a string
!
String input = "123678";
^
|
int indexOfSeven = 4;
int x = Convert.ToInt32(input[indexOfSeven]); // Returns 55
int x = Convert.ToInt32(input[indexOfSeven].toString()); // Returns 7
In C# v.7 you could use an inline out parameter, without an additional variable declaration:
int.TryParse(TextBoxD1.Text, out int x);
int.TryParse()
It won't throw if the text is not numeric.
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
You can write your own extension method
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
And wherever in code just call
int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null
In this concrete case
int yourValue = TextBoxD1.Text.ParseInt();
You can try the following. It will work:
int x = Convert.ToInt32(TextBoxD1.Text);
The string value in the variable TextBoxD1.Text will be converted into Int32 and will be stored in x.