如何使用if语句作为数字范围

时间:2017-01-27 15:03:05

标签: c#

我有TextBox,用户在其中写下数字1-12代表月份。我目前的代码如下:

int month;
month = int.Parse(textbox.Text);
if (month >= 1 && month <= 12) {
    // Do stuff
}

如果用户的条目有效(1-12),这将执行预期的操作,但它不会阻止他们首先输入无效的输入。有没有办法约束文本框以强制用户首先输入数字1-12?

1 个答案:

答案 0 :(得分:0)

一件简单的事情就是这样做:

// You might want to consider using int.TryParse here instead because if
// the user accidentally wrote something other than an int this'll throw
// an exception
int month = int.Parse(textbox.Text);
if (month >= 1 && month <= 12)
{
    //dostuff
}
else {
  // Show dialog box prompting the user to enter 1 - 12
}

更好的解决方案是在UI库中使用其中一种验证机制。您没有标记您正在使用的是哪一个,但是您可以看到this article有关如何约束文本框的WPF示例。

如果您只是要求用户在少量选项之间进行选择,您也可以考虑使用下拉菜单。 (单选按钮也是一个选项,但只有你选择的数量非常少,它们才有意义,最多3到4是我的一般经验法则,所以我不认为它们在这里是个不错的选择)。