将字符串转换为整数C#
我想将输入的字符串转换为int。我曾尝试int.parse,并int.parse32但是当我按 “回车” 我得到以下错误:将字符串转换为整数C#
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类:形式:
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
到文本框的文本的任何更改将不会反映在可变currentID
this.orderID.Text = currentID;
需要在EnterKey
功能做的是用直接的文本框的值:
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;
}
}
谢谢,这帮助了我很多,并教我一个新的东西以及。 :) – 2013-05-14 07:30:55
@AlexMoreno很高兴我能帮到你。 – Magnus 2013-05-14 07:31:29
检查字符串string.IsNullOrEmpty()
并且不要试图解析这样的字符串。
我想提及更新的'string.IsNullOrWhitespace()'方法(自C#4.0以来),为用户做了一些额外的检查:)。 – Destrictor 2013-05-14 07:35:40
好消息,谢谢。 – Hikiko 2013-05-14 07:43:30
使用TryParse
,而不是直接将值解析:
int intResult = 0;
if (Int32.TryParse(yourString, out intResult) == true)
{
// do whatever you want...
}
试试这个代码
if (!string.IsNullOrEmpty(currentID)){
newCurrentID = int.Parse(currentID);
}
你有更好的选择使用TryParse .... – 2013-05-14 07:17:22
同意您的意见谢谢 – 2013-05-14 07:17:58
把一个破发点,以法'EnterKey',看看'currentID'包含。 – I4V 2013-05-14 07:11:09
currentID是什么类型,它的内容是什么? – 2013-05-14 07:12:04
当你解析它时你在currentID里面找到了什么 – tariq 2013-05-14 07:14:29