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 also may use an extension method, so it will be more readable (although everybody is already used to the regular Parse functions).
public static class StringExtensions
{
///
/// Converts a string to int.
///
/// The string to convert.
/// The converted integer.
public static int ParseToInt32(this string value)
{
return int.Parse(value);
}
///
/// Checks whether the value is integer.
///
/// The string to check.
/// The out int parameter.
/// true if the value is an integer; otherwise, false.
public static bool TryParseToInt32(this string value, out int result)
{
return int.TryParse(value, out result);
}
}
And then you can call it that way:
If you are sure that your string is an integer, like "50".
int num = TextBoxD1.Text.ParseToInt32();
If you are not sure and want to prevent crashes.
int num;
if (TextBoxD1.Text.TryParseToInt32(out num))
{
//The parse was successful, the num has the parsed value.
}
To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.