How can I convert String to Int?

2018-12-31 01:54发布

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?

28条回答
素衣白纱
2楼-- · 2018-12-31 02:32

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 ;
}
查看更多
何处买醉
3楼-- · 2018-12-31 02:34
Convert.ToInt32( TextBoxD1.Text );

Use this if you feel confident that the contents of the text box is a valid int. A safer option is

int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );

This will provide you with some default value you can use. Int32.TryParse also returns a boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an if statement.

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}
查看更多
还给你的自由
4楼-- · 2018-12-31 02:34

The most simple way is to use an extension helper like this:

public static class StrExtensions
{
  public static int ToInt(this string s, int defVal = 0) => int.TryParse(s, out var v) ? v : defVal;
  public static int? ToNullableInt(this string s, int? defVal = null) => int.TryParse(s, out var v) ? v : defVal;
}

Usage is so simple:

var x = "123".ToInt(); // 123
var y = "abc".ToInt(); // 0

string t = null;
var z = t.ToInt(-1); // -1
var w = "abc".ToNullableInt(); // null
查看更多
君临天下
5楼-- · 2018-12-31 02:37

While there are already many solutions here that describe int.Parse, there's something important missing in all the answers. Typically, the string representations of numeric values differ by culture. Elements of numeric strings such as currency symbols, group (or thousands) separators, and decimal separators all vary by culture.

If you want to create a robust way to parse a string to an integer, it's therefore important to take the culture information into account. If you don't, the current culture settings will be used. That might give a user a pretty nasty surprise -- or even worse, if you're parsing file formats. If you just want English parsing, it's best to simply make it explicit, by specifying the culture settings to use:

var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
    // use result...
}

For more information, read up on CultureInfo, specifically NumberFormatInfo on MSDN.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 02:38

You can try this, 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.

查看更多
与风俱净
7楼-- · 2018-12-31 02:39
int i = Convert.ToInt32(TextBoxD1.Text);
查看更多
登录 后发表回答