C# 无法将字符串转换为 int。错误消息:输入字符串的格式不正确
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1339599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Not able to cast string to int. Error msg: Input string was not in a correct format
提问by Steven
I havethe following code which outputs the number '40':
我有以下代码输出数字“40”:
Hashtable ht = new Hashtable();
ht.Add("numRooms", pageData.Property["romtotalt"].ToString());
string str = ht["numRooms"].ToString();
lblMigrate.Text = i.ToString();
Then I try to convert the string to an int, and I get an exception / error:
然后我尝试将字符串转换为 int,但出现异常/错误:
Hashtable ht = new Hashtable();
ht.Add("numRooms", pageData.Property["romtotalt"].ToString());
string str = ht["numRooms"].ToString();
int i = Convert.ToInt32(str); // <-- This is where it fails I t hink. But why??
lblMigrate.Text = i.ToString();
This is the error message I get:
这是我收到的错误消息:
Server Error in '/' Application.
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a correct format.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[FormatException: Input string was not in a correct format.]
System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +7469351
System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +119
development.templates.HotellGuide.btnMigrateHotels_Click(Object sender, EventArgs e) +956
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
I don't understand what's wrong. I'va castet string to int multiple times before, and never has this problem occured.
我不明白出了什么问题。我以前多次将 castet string 转换为 int,但从未发生过此问题。
Please help :)
请帮忙 :)
Update
更新
I have found a solution. I have NO idea why this works.... but it works...
I put the convertion inside a Try Catch, and now it works. Figure that one out :op
我找到了解决办法。我不知道为什么会这样......但它有效......
我将转换放在 Try Catch 中,现在它可以工作了。找出一个:op
int numRooms = 0;
int numAllergyRooms = 0;
try
{
numRooms = Convert.ToInt32(newHotel["numRooms"].ToString().Trim());
numAllergyRooms = Convert.ToInt32(newHotel["numAllergyRooms"].ToString().Trim());
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
采纳答案by erelender
I think the line "Input string was not in a correct format" explains it all. In the line
我认为“输入字符串的格式不正确”这一行说明了一切。在行中
int i = Convert.ToInt32(str);
str might be containing alphabetic characters. Take a look at it while debugging, what does it contain?
str 可能包含字母字符。调试的时候看看,里面有什么内容?
回答by Wael Dalloul
The code is ok, but if the str may have white space, so you should remove them before convert:
代码没问题,但如果 str 可能有空格,那么你应该在转换之前删除它们:
int i = Convert.ToInt32(str.Replace(" " ,"")); // <-- This is where it fails I t hink. But why??
回答by Seb Nilsson
You should add Trim() to your code-line where you think it fails. It probably has to do with excessive spaces.
您应该将 Trim() 添加到您认为失败的代码行中。这可能与过多的空间有关。
int i = Convert.ToInt32(str.Trim());
Maybe even check to see if stris string.Empty, this will also cause Convert.ToInt32 to crash.
甚至可能检查str是否为string.Empty,这也会导致 Convert.ToInt32 崩溃。
if (string.IsNullOrEmpty(str)) {
str = "0";
}
回答by Mohammad Motaghi
I had the same problem but only try catch method solved my problem
我有同样的问题,但只有 try catch 方法解决了我的问题
try
{
decimal dPrice=Convert.ToDecimal(sPrice);
decimal dFreight = Convert.ToDecimal(sFreight);
decimal dLocalship = Convert.ToDecimal(sLocalship);
decimal dTarrif = Convert.ToDecimal(sTarrif);
decimal dBenefit = Convert.ToDecimal(sBenefit);
decimal dTax = Convert.ToDecimal(sTax);
decimal dVat = Convert.ToDecimal(sVat);
decimal dConv = Convert.ToDecimal(sConv);
decimal factors=(dTarrif+dBenefit+dTax+dVat)/100+1;
decimal dTotal=(dPrice+dFreight)*dConv;
dTotal=dTotal*factors;
string st = Convert.ToString(dTotal);
e.Row.Cells[iCell].Text = "price is: " + st + " Rials";
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
回答by gazma
It will be that you are trying to convert Nulls or in this case "" (after your .ToString()
) to an int.
这将是您试图将 Nulls 或在这种情况下“”(在您的 之后.ToString()
)转换为 int。
Try something that will insert an acceptable placeholder for nulls such as -1 shown in the code below.
尝试一些可以为空值插入可接受占位符的操作,例如下面代码中显示的 -1。
Convert.ToInt32(newHotel["numAllergyRooms"].ToString().Trim() == "" ? "-1" : newHotel["numAllergyRooms"].ToString().Trim());
回答by Ronny D'Hoore
The cause might also be a registry problem. See https://support.microsoft.com/en-us/help/942460/system-formatexception-occurs-when-attempting-to-convert-a-numeric-str
原因也可能是注册表问题。请参阅https://support.microsoft.com/en-us/help/942460/system-formatexception-occurs-when-attempting-to-convert-a-numeric-str
They explain that a proper number string might still fail to convert if the value HKEY_CURRENT_USER\Control Panel\International\sPositiveSign contains something bad. In our parts of the world, the value for this key should be empty (no space, just empty).
他们解释说,如果值 HKEY_CURRENT_USER\Control Panel\International\sPositiveSign 包含错误的内容,则正确的数字字符串可能仍无法转换。在我们的世界中,这个键的值应该是空的(没有空格,只是空的)。
Probably that was not your problem, but I'm adding it here for someone who might be having exactly this as the cause for their problem...
可能那不是你的问题,但我在这里添加它给那些可能正是因为这个问题导致他们问题的人......