Skip to main content
 首页 » 编程设计

c#之使用子字符串验证文本框的最后 4 位数字 C#(vb6 右函数)

2024年02月20日23cloudgamer

我正在尝试验证日期文本框以确保输入了正确的日期格式。

我转换了这段 vb6 代码:

If (IsDate(txtBirthDate)) And (IsNumeric(Right(txtBirthDate, 4)))) 

进入此 C# 代码 -

int output = 1; 
DateTime output2; 
 
if ((! DateTime.TryParse(txtBirthDate.Text, out output2)) & (!int.TryParse((txtBirthDate.Text.Substring(txtBirthDate.Text.Length - 5)), out output)))  
{ 
    MessageBox.Show("error") 
} 

我试图做的是确保日期文本框的最后 4 位数字是数字(年份 - 即 1990 年 5 月 10 日的 1990 年),如果不是数字,则显示错误。尽管由于日期格式中的“/”,我无法验证所有内容都是数字。

代码未显示错误并构建。但是当我调试应用程序时,我收到一个错误。错误状态:

Index and length must refer to a location within the string.
Parameter name: length.

关于如何实现这一点有什么想法吗?

请您参考如下方法:

要检查日期是否为特定格式,请使用 DateTime.TryParseExact():

if (!DateTime.TryParseExact(output , "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out output2))  
{ 
    MessageBox.Show("error") 
} 

编辑:根据您的需要更改格式:

“d/M/yyyy” 代表英国,“M/d/yyyy” 代表美国