C# 检查NumericUpDown是否为空
如何检查用户是否将C# 检查NumericUpDown是否为空,c#,numericupdown,C#,Numericupdown,如何检查用户是否将NumericUpDown控件留空,并删除其上的值? 因此,我可以将其重新赋值为0。使用已验证事件并请求text属性可能会很有用 if(NumericUpDown1.Text == "") { // If the value in the numeric updown is an empty string, replace with 0. NumericUpDown1.Text = "0"; } private void myNumericUpDown_V
NumericUpDown
控件留空,并删除其上的值?
因此,我可以将其重新赋值为0。使用已验证事件并请求text属性可能会很有用
if(NumericUpDown1.Text == "")
{
// If the value in the numeric updown is an empty string, replace with 0.
NumericUpDown1.Text = "0";
}
private void myNumericUpDown_Validated(object sender, EventArgs e)
{
if (myNumericUpDown.Text == "")
{
myNumericUpDown.Text = "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;
}
}
即使用户删除了
numericUpDown
控件的内容,其值仍然保持不变。upDown.Text
将是“”,但upDown.Value
将是之前输入的有效值。因此,为了“防止”用户将控件留空,在
onLeave
事件中,我设置:
upDown.Text = upDown.Value.ToString();
您可以尝试以下方法:
if(numericUpDown.Value == 0){
MessageBox.Show(
"Please insert a value.",
"Required", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation
);
return;
}
检查变量的长度-请注意,Visual studio不会显示“Text”属性,但您可以键入它,它将进行编译。还有其他一些答案提供了OP的问题,它们是在一段时间前发布的。在发布答案时,请确保添加新的解决方案或更好的解释,尤其是在回答旧问题时。
upDown.Text = upDown.Value.ToString();
if(numericUpDown.Value == 0){
MessageBox.Show(
"Please insert a value.",
"Required", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation
);
return;
}