How can I convert String to Int?

后端 未结 30 2135
情歌与酒
情歌与酒 2020-11-21 05:35

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?

30条回答
  •  清酒与你
    2020-11-21 06:15

    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(..);
    }
    

提交回复
热议问题