NumericUpDown错误MessageBox

时间:2015-05-15 23:32:14

标签: c# winforms messagebox numericupdown

我想问一下我应该将哪些代码插入到我的" numGPA"告知用户他们已超过"最大值"。

现在,如果尝试"提交"一个超过最大值的值,我的视觉工作室只会播放一个" ding"声音。

而不是我希望有一个类似&#34的消息框;只允许从0到4的值"

我在Google上发现了这段代码,尽管我将numericUpDown1更改为numGPA但它无效。

        if (numGPA.Value >= 4 || numGPA.Value <= 0)
        {
            MessageBox.Show("Error. Number must be between 0 and 4");
            numGPA.Value = 1;
            numGPA.ReadOnly = true;
        }

请查看此视频,以清楚了解我的观点 https://www.youtube.com/watch?v=XVv-it6x044&feature=youtu.be

而不是&#34; ding&#34;声音效果播放@ 0.06,我想要一个MessageBox。

2 个答案:

答案 0 :(得分:0)

您可以使用TextChange事件执行此操作。您可以(也应该)设置最小和最大属性以使用箭头限制输入。

Private Sub NumericUpDown1_Changed(sender As Object, e As EventArgs) Handles NumericUpDown1.TextChanged
If IsNumeric(NumericUpDown1.Text) AndAlso _
  CInt(NumericUpDown1.Text) > NumericUpDown1.Maximum Then MsgBox("Oops! Too big.")
End Sub

答案 1 :(得分:0)

最好的方法是让用户编辑并仅检查他何时完成。这将触发ValueChanged事件。

在这里,我们可以通过抓取内部TextBox控件来获取输入的值。

我建议使用辅助函数,可能是这样的:

void nudCheck(NumericUpDown nud)
{
    TextBox tb = (TextBox) nud.Controls[1];
    if (Convert.ToInt32(tb.Text) > nud.Maximum)
    {
        string msg = tb.Text + " is too large! Setting value to maximum: " + nud.Maximum;
        tb.Text = "" + nud.Maximum;
        nud.Value = nud.Maximum;
        // do what you want with the message string!
        //MessageBox.Show(msg);   // not recommended!
        toolTip1.Show(msg, nud);  // add a ToolTip component to your form for this!
    }
}

在这里打电话:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    nudCheck(numericUpDown1);
}

我们还希望在用户按下Enter时抑制错误声音,最好是KeyDown事件。

private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.Enter) 
   {
       nudCheck(numericUpDown1);
       e.SuppressKeyPress = true;
   }
}

请注意,调出实际的MessageBox会带回铃声,并强制用户摆脱它。所以我使用了ToolTip,但如果你有空间,Label也会有效。

显然,您可能需要添加类似的代码来检查输入低于Minimum ..

相关问题