C#-Tryparse无法正常工作 [英] C# -Tryparse not working

查看:156
本文介绍了C#-Tryparse无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在验证出生日期时,如果月份包含字符串或字符, int32.tryparse 将返回false,该值应为true,代码将移至else部分。



我希望用户使用 DD MM YYYY 格式和数字,例如12 02 2014.对于测试。我在月份字段中输入了一个字符串,但它没有抛出错误。我的输入是12 sx 2014.



有人可以对此有所了解。



 if(dobMonth.Text == String.Empty ||!Int32.TryParse(dobMonth.Text,out intParsed))
{
valid = false;
dobMonth.CssClass =error;
ErrDOB.Visible = true;
}
其他
{
}

< div>< label>出生日期:< span class =req-field > * LT; /跨度>< /标签>< / DIV>

< div>< span>< asp:TextBox ID =txtDOBDayText =DDMaxLength =2runat =server/>< / span>< ; / DIV>

< div>< span>< asp:TextBox ID =txtDOBMonthText =MMMaxLength =2runat =server/>< / span>< ; / DIV>
< div>< span>< asp:TextBox ID =txtDOBYearText =YYYYMaxLength =4runat =server/>< / span>< / div>

解决方案

注意ID不匹配:dobMonth vs txtDOBMonth。

您可能想要使用 DateTime.TryParseExact方法 [ ^ ]。


< blockquote> Int32.TryParse将尝试将ENTIRE字符串转换为整数。您声称输入的内容为12 sx 1024,而不是有效整数,因此TryParse返回false。


while validating date of birth,if the month contains string or character,int32.tryparse returns false,which should be true and the code moves to else part.

I want the user to use DD MM YYYY format and numeric like 12 02 2014.For testing.I entered a string in the month field but it is not throwing error.My input was 12 sx 2014.

Can someone shed some light on this.

if (dobMonth.Text == String.Empty || !Int32.TryParse(dobMonth.Text, out intParsed))
{
valid = false;
dobMonth.CssClass = "error";
ErrDOB.Visible = true;
}
else
{
}

<div><label>Date of Birth:<span class="req-field">*</span></label></div>

<div><span><asp:TextBox ID="txtDOBDay" Text="DD" MaxLength="2" runat="server" /></span></div>

<div><span><asp:TextBox ID="txtDOBMonth" Text="MM" MaxLength="2" runat="server" /></span></div>                              
<div><span><asp:TextBox ID="txtDOBYear" Text="YYYY" MaxLength="4"       runat="server" /></span></div>

解决方案

Notice a mismatch of ID: dobMonth vs txtDOBMonth.
You may want to use DateTime.TryParseExact Method[^] instead.


Int32.TryParse will try to convert the ENTIRE string to an integer. What you're claiming as your input, "12 sx 1024", in not a valid integer so TryParse returns false.


这篇关于C#-Tryparse无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆