gpt4 book ai didi

c# - 无法将字符串转换为 int。错误消息 : Input string was not in a correct format

转载 作者:太空狗 更新时间:2023-10-29 21:11:24 25 4
gpt4 key购买 nike

我有以下输出数字“40”的代码:

Hashtable ht = new Hashtable();
ht.Add("numRooms", pageData.Property["romtotalt"].ToString());
string str = ht["numRooms"].ToString();
lblMigrate.Text = i.ToString();

然后我尝试将字符串转换为 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();

这是我收到的错误信息:

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

我不明白这是怎么回事。我之前多次将 string 转换为 int,从来没有出现过这个问题。

请帮忙:)

更新

我找到了解决办法。我不知道为什么这行得通……但它行得通……
我将转换放在 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);
}

最佳答案

我认为“输入字符串的格式不正确”这一行说明了一切。在行中

 int i = Convert.ToInt32(str);

str 可能包含字母字符。边调试边看,里面有什么?

关于c# - 无法将字符串转换为 int。错误消息 : Input string was not in a correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1339599/

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