将String转换为Int c#

本文关键字:Int 转换 String | 更新日期: 2023-09-27 18:13:19

我正在尝试将输入的字符串转换为整型。我试过int。解析int。parse32但是当我按"enter"时,我得到以下错误:

System.FormatException: Input string was not in a correct format.
  at System.Number.StringToNumber(String str, NumberStyles options, 
                                  NumberBuffer & number...."

局部类Form1:

this.orderID.Text = currentID;
this.orderID.KeyPress += new KeyPressEventHandler(EnterKey);

部分类Form1:Form:

  public int newCurrentID;
  private void EnterKey(object o, KeyPressEventArgs e)
    {
        if(e.KeyChar == (char)Keys.Enter)
        {
            try
            {
                newCurrentID = int.Parse(currentID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            e.Handled = true;
        }
    }

将String转换为Int c#

字符串是不可变的,所以当您将currentID分配给文本框时,该文本的任何更改都不会反映在变量currentID

this.orderID.Text = currentID;

EnterKey函数中需要做的是直接使用Textbox的值:

private void EnterKey(object o, KeyPressEventArgs e)
{
        if(e.KeyChar == (char)Keys.Enter)
        { 
            if(!int.TryParse(orderID.Text, out newCurrentID))
               MessageBox.Show("Not a number");
            e.Handled = true;
        }
 }

检查string.IsNullOrEmpty()字符串,不要尝试解析此类字符串

使用TryParse代替直接解析值:

int intResult = 0;
if (Int32.TryParse(yourString, out intResult) == true)
{
    // do whatever you want...
}

试试这个代码

if (!string.IsNullOrEmpty(currentID)){
     newCurrentID = int.Parse(currentID);
}