gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:04 25 4
gpt4 key购买 nike

我正在尝试将输入的字符串转换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com