如何在Visual Basic中将文本框中的字符串检查为整数?(How can I check string in textbox as integer in Visual Basic?)

编程入门 行业动态 更新时间:2024-10-25 17:17:59
如何在Visual Basic中将文本框中的字符串检查为整数?(How can I check string in textbox as integer in Visual Basic?)

我有3个文本框(日,月,年),我想检查输入是否例如,日必须是1到31,依此类推。

我的代码是:

If InputDan.Text < "1" Or InputDan > "31" Then Warning.Text = "Not a valid day input." Else Warning.Text = ""

此外,我有日期和月份输入限制为2个字符,年份为4个。它适用于10到31之间的数字,当输入为0或32并且打开时,它会正确地发出警告消息。

这是问题......

当我输入4到9的数字时,它会发出一条警告信息,因为我后来发现该程序在一个字符输入为0后认为是空的。所以如果我输入4,程序会把它读成40,依此类推。

以某种方式将String输入转换为Int可以解决这个问题吗?

I have 3 textboxes (day, month, year) and I want to check if input is e.g. day has to be from 1 to 31 and so on.

My code is:

If InputDan.Text < "1" Or InputDan > "31" Then Warning.Text = "Not a valid day input." Else Warning.Text = ""

Also I have day and month input limited to 2 characters and year to 4. It works fine with numbers from 10 to 31 and it properly puts an warning message when input is 0 or 32 and on.

Here's the problem...

When I put in numbers from 4 to 9 it puts on a warning message, as I figured out later that program considers empty space after one character input as 0. So if I enter 4 the program will read it as 40, and so on.

Can I solve this problem with converting String input as Int somehow?

最满意答案

在比较数字之前,您需要将数字解析为整数,否则>"11"将按字母顺序进行比较,而不是按数字顺序进行比较。

Dim day As Integer Dim valid As Boolean = Int32.TryParse(InputDan.Text, day)

现在您知道该输入是否是正确的数字,如果不是,您可以显示警告。

我建议采用不同的方法来检查输入是否是正确的一天,因为您必须考虑该月的天数(也是闰年,不同的日历等)。 因此,请使用当前文化的日历,并以这种方式查看给定月份的天数是否正确:

Dim daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month) If day > daysInMonth OrElse day < 1 Then ' show warning ' End If

(假设您已经使用Int32.TryParse检查了年份和月份部分)

You need to parse the numbers to integer before you can compare them, otherwise >"11" will compare them alphabetically and not by their numerical order.

Dim day As Integer Dim valid As Boolean = Int32.TryParse(InputDan.Text, day)

Now you know if that input was a correct number and you could show a warning if it was not.

I would suggest a different approach to check whether or not the input was a correct day since you must take the number of days in that month into account(also leap years, different calendars etc). So use the current culture's calendar and look if the number of days is correct for the given month in this way:

Dim daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month) If day > daysInMonth OrElse day < 1 Then ' show warning ' End If

(assuming you have already checked the year and month part with Int32.TryParse)

更多推荐

本文发布于:2023-07-31 20:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   中将   框中   文本

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!