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