我该如何检查用户是否将 NumericUpDown
控件清空,从而移除其上的值?这样我就可以重新分配一个值为 0。
我该如何检查用户是否将 NumericUpDown
控件清空,从而移除其上的值?这样我就可以重新分配一个值为 0。
if(NumericUpDown1.Text == "")
{
// If the value in the numeric updown is an empty string, replace with 0.
NumericUpDown1.Text = "0";
}
使用validated事件并请求文本属性可能会有所帮助。
private void myNumericUpDown_Validated(object sender, EventArgs e)
{
if (myNumericUpDown.Text == "")
{
myNumericUpDown.Text = "0";
}
}
numericUpDown
控件的内容,其值仍然存在。upDown.Text
将会是"",但是upDown.Value
将是先前输入的有效值。onLeave
事件中,“防止”用户留空控件的方法是设置:upDown.Text = upDown.Value.ToString();
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;
}
}
decimal d = 0
if(decimal.TryParse(NumericUpDown1.Text, out d)
{
}
NumericUpDown1.Value = d;
if (string.IsNullOrEmpty(((Control)this.nud1).Text))
{
//null
}
else
{
//have value
}
if(numericUpDown.Value == 0){
MessageBox.Show(
"Please insert a value.",
"Required", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation
);
return;
}