c# - 将字符串转换为 Int C#

标签 c#

我正在尝试将输入的字符串转换为 int。我试过 int.parse , 和 int.parse32 但是当我按“输入”时,我收到以下错误:

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;
        }
    }

最佳答案

字符串是不可变的,所以当你分配 currentID对文本框的任何更改都不会反射(reflect)在变量 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;
        }
 }

关于c# - 将字符串转换为 Int C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16537110/

相关文章:

c# - 多个表的通用批量更新

Win32_PhysicalMemory 上的 C# NullReferenceException

c# - 身份服务器 4 AddInMemoryIdentityResources

c# - 如何在 C# 中确定 SharePoint 服务应用程序正在哪个应用程序池上运行?

c# - 如何在 Windows 窗体应用程序中迭代控件?

c# - 如何从 IIS 上托管的 .net 代码访问 key 保管库 secret

c# - 了解 Entity Framework 4.1 约定

c# - 从 Winform 显示 pdf 文件

c# - 在 C# 中合并多个 TIF 文件

c# - 带有用户输入验证的 KeyDown 事件