Under certain conditions I'd like to cancel the ValueChanged
event of a NumericUpDown
control in Winforms (eg when the value set in the control is too high in relation to another value in a TextBox
).
However, the EventArgs
passed as argument into the event handler for the NumericUpDown
control doesn't offer anything like "Cancel", so how can I do it?
private void nudMyControl_ValueChanged(object sender, EventArgs e)
{
// Do some stuff, but only if the value is within a certain range.
// Otherwise, cancel without doing anything.
}
You probably can handle this situation by using Minimum
& maximum
Properties, yet there are some solutions.
One way to do it is by creating a custom control, although it is nasty in my idea.
public partial class CustomNumericUpDown : NumericUpDown
{
public CustomNumericUpDown()
{
InitializeComponent();
}
protected override void OnTextBoxKeyDown(object source, KeyEventArgs e)
{
if (MyCustomCondition())
{
e.Handled = true;
}
base.OnTextBoxKeyDown(source, e);
}
private bool MyCustomCondition()
{
var checkOut = false;
//if (something == foo)
//{
checkOut = true;
//}
return checkOut;
}
}
You also can do stuff for ValueChanged
:
This is some dummy sample, yet you can change it in your way:
public virtual decimal CurrentEditValue { get; internal set; } = 0M;
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (decimal.TryParse(Text, out decimal v))
{
CurrentEditValue = v;
OnValueChanged(e);
}
}
protected override void OnValueChanged(EventArgs e)
{
// if(CurrentEditValue == foo) Do_stuff.
base.OnValueChanged(e);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.