2013-02-25 197 views
5

如何檢查用戶是否將NumericUpDown控件留空,並刪除其值? 因此,我可以重新分配它的0檢查NumericUpDown是否爲空

+0

檢查變量的長度 - http://www.dotnetperls.com/string-length – 2013-02-25 18:51:01

回答

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

} 
NumericUpDown1.Value = d; 
4

值使用驗證的事件,並要求文本屬性

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

試試這個

這可能是有用的
if (string.IsNullOrEmpty(((Control)this.nud1).Text)) 
{ 
    //null 
} 
else 
{ 
    //have value 
} 
0

如果你w螞蟻禁止NumericUpDown爲空值,只需使用這個類。其效果是,一旦用戶試圖通過全選+退格鍵刪除控制值,則實際數值將再次設置。這並不是一個煩惱,因爲用戶仍然可以通過select-all +鍵入數字數字開始編輯新的數值。

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; 
    } 
    }