[英]Converting String to Int C#
我正在尝试将输入的字符串转换为int。 我已经尝试过int.parse和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是否为string.IsNullOrEmpty()
,不要尝试解析此类字符串。
字符串是不可变的,因此当您将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;
}
}
使用TryParse
而不是直接解析值:
int intResult = 0;
if (Int32.TryParse(yourString, out intResult) == true)
{
// do whatever you want...
}
试试这个代码
if (!string.IsNullOrEmpty(currentID)){
newCurrentID = int.Parse(currentID);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.