检查 NumericUpDown 是否为空。

7

我该如何检查用户是否将 NumericUpDown 控件清空,从而移除其上的值?这样我就可以重新分配一个值为 0。


检查变量的长度 - http://www.dotnetperls.com/string-length - Matt Busche
7个回答

10
if(NumericUpDown1.Text == "")
{
     // If the value in the numeric updown is an empty string, replace with 0.
     NumericUpDown1.Text = "0";
}

2
请注意,Visual Studio 不会显示“Text”属性,但您仍然可以键入它并进行编译。 - Maxter

8

使用validated事件并请求文本属性可能会有所帮助。

private void myNumericUpDown_Validated(object sender, EventArgs e)
{
    if (myNumericUpDown.Text == "")
    {
        myNumericUpDown.Text = "0";
    }
}

2
即使用户删除了numericUpDown控件的内容,其值仍然存在。
upDown.Text将会是"",但是upDown.Value将是先前输入的有效值。
因此,在onLeave事件中,“防止”用户留空控件的方法是设置:
upDown.Text = upDown.Value.ToString();

0
如果您想禁止NumericUpDown的空值,只需使用此类。它的效果是,一旦用户尝试使用全选+退格键擦除控件值,实际数字值将再次设置。这并不是真正的烦恼,因为用户仍然可以全选+输入数字来开始编辑新的数字值。
  sealed class NumericUpDownEmptyValueForbidder {
     internal NumericUpDownEmptyValueForbidder(NumericUpDown numericUpDown) {
        Debug.Assert(numericUpDown != null);
        m_NumericUpDown = numericUpDown;
        m_NumericUpDown.MouseUp += delegate { Update(); };
        m_NumericUpDown.KeyUp += delegate { Update(); };
        m_NumericUpDown.ValueChanged += delegate { Update(); };
        m_NumericUpDown.Enter += delegate { Update(); };
     }
     readonly NumericUpDown m_NumericUpDown;
     string m_LastKnownValueText;

     internal void Update() {
        var text = m_NumericUpDown.Text;
        if (text.Length == 0) {
           if (!string.IsNullOrEmpty(m_LastKnownValueText)) {
              m_NumericUpDown.Text = m_LastKnownValueText;
           }
           return;
        }
        Debug.Assert(text.Length > 0);
        m_LastKnownValueText = text;
     }
  }

0
decimal d = 0 
if(decimal.TryParse(NumericUpDown1.Text, out d)
{

}
NumericUpDown1.Value = d;

0
尝试这个。
if (string.IsNullOrEmpty(((Control)this.nud1).Text))
{
  //null
}
else
{
  //have value
}

0
你可以尝试这个:
if(numericUpDown.Value == 0){

 MessageBox.Show(
   "Please insert a value.", 
   "Required", MessageBoxButtons.OK, 
   MessageBoxIcon.Exclamation
 );

 return;

}

还有其他答案可以回答提问者的问题,而且它们是一段时间之前发布的。当您发布答案时,请确保添加一个新的解决方案或更加详细的解释,特别是在回答旧问题时。参见:如何撰写好的答案? - help-info.de

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接