如何设置最大和最小数量可以在C#中的TextBox中输入

how to set maximum and minimum number can be entered in a TextBox in C#

我想要一个只能显示 1-24 个数字的文本框。我希望它检查第一个数字,因为它也必须是 1 或 2。如果用户提供任何其他输入,它将在消息框中显示警告。 这是我试过的代码:

private void textBox2_TextChanged(object sender, EventArgs e)
{
    int hour;
    bool ishourValid = int.TryParse(textBox2.Text, out hour);

    // Check the Text value if it's only numbers
    if (System.Text.RegularExpressions.Regex.IsMatch(textBox2.Text, "[^0-9]"))
    {
        // Clear the text box as it wasn't a number
        textBox2.Clear();
        // Show Warning MesssageBox
        MessageBox.Show("Please enter numbers only!");
    }
    // Check TextBox text length
    else if (textBox2.Text.Length >= 2)
    {
        textBox6.Focus();
    }
    else if (Hour < 1 && Hour > 24)
    {
        MessageBox.Show("Please use 24-hour format!");
    }
}

一切正常,但此代码无效:

else if (Hour < 1 && Hour > 24)
{
    MessageBox.Show("Please use 24-hour format!");
}

请帮帮我

一开始你尝试解析来自textBox2.Text的字符串值并将其存储到'hour'.

int hour;
bool ishourValid = int.TryParse(textBox2.Text, out hour);

稍后您正在检查 Hour... 否则如果(小时 < 1 && 小时 > 24) { MessageBox.Show("Please use 24-hour format!"); }

但是你还没有设置Hour。你设置 hour。我看不到 Hour 在哪里定义;如果您能够编译,它必须在某个地方。我的猜测是您的代码没有按预期工作,因为您需要类似的东西:

Hour = hour;

或将您的 TryParse 更改为使用 Hour...

bool ishourValid = int.TryParse(txt, out Hour);

话虽如此,我认为还有一些问题。这可能更适合代码审查堆栈?

如果您不将 hour 大写,也许代码可以运行?再加上看起来评估正在寻找同时小于 1 和大于 24 的答案。

旧: else if (Hour < 1 && Hour > 24)

新: else if (hour < 1 || hour > 24)

您需要 || (OR) 条件而不是 AND 条件。将您的代码更改为如下所示,否则 Hour 的值在任何时间点都不能保持两个边界值。意思是说,如果 Hour < 1 那么它不可能大于 24,并且您的条件必然会被评估为 false。

else if (Hour < 1 || Hour > 24)
{
    MessageBox.Show("Please use 24-hour format!");
}