C#ASP.NET中的输入字符串格式不正确 [英] Input string was not in correct format in C# ASP.NET
本文介绍了C#ASP.NET中的输入字符串格式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
protected void Page_Load(object sender, EventArgs e)
{
string score = Request.QueryString["Score"];
Label1.Text = score;
int value = Convert.ToInt32(score);
if (value >= 10)
{
Label2.Text = "Cheers ! your score is satisfactory to promote you for the next level. All the best for the Next Move.";
}
else
{
Label2.Text = "Sorry ! Your score is not satisfactory to promote you for the next level. You can again attempt this level after Seven Days.";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int level = Convert.ToInt32(Request.QueryString["level"]);
Response.Redirect("Toplist.aspx?level=" + level);
}
}
我的尝试:
int value = Convert.ToInt32(得分);在这行错误(输入字符串格式不正确)
What I have tried:
int value = Convert.ToInt32(score); in this line error(Input string was not in correct format)
推荐答案
嗯,你期待什么?查看得分
的值。试想一下:
Well, what did you expect? Look at the value ofscore
. Just imagine:
string score = "Blah!";
int value = Convert.ToInt32(score);
应该引起异常。
其他问题可能是由本地化引起的。一千可写为 1,000
或 1.000
或 1 000
或 1000
或...
正如 Bernhard Hiller 已经指出的那样,尝试将字符串转换为一个数字可以提出一个斧头。因此(健壮的)代码应该处理这种情况。将字符串转换为整数时,您基本上有两个选项:
As already noted by Bernhard Hiller trying to convert a string to a number can raise an axception. Hence (robust) code should handle such a case. When converting a string to an integer you have basically two options:
- 处理异常(您可以在文档中找到代码示例:Convert.ToInt32 Method(String)(System) [ ^ ])。
- 使用Int32.TryParse方法(文档 Int32.TryParse方法(String,Int32)(系统) [ ^ ]也提供了代码示例。
- Handle the exception (you may find code sample inside the very documentation: Convert.ToInt32 Method (String) (System)[^]).
- Use the Int32.TryParse method (the documentation Int32.TryParse Method (String, Int32) (System)[^] provides a code sample as well).
这篇关于C#ASP.NET中的输入字符串格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文