Dhanapal
Dhanapal

Reputation: 14507

C#, winform - NumericUpDown max limit not validated on KeyPress?

Using NumericUpDown control of C# winform application.

Set Maximun value as 99. But when I type value above 99, eg: 555, it allows me to key (key_press event )in values 555 and it changes back to max value (99) only if i leave the control. What i need is, user should not allowed to key in values more than 99. And also the default behaviour 'Up and Down action' values should not be affected by this. How do i do this?

Upvotes: 3

Views: 5107

Answers (4)

Badrinath Ajabe
Badrinath Ajabe

Reputation: 3

When we have used numericupdown control in c#, with the keypress, keydown/up events when you wanted to restrict the digit length limit in control like 2,3,4 ...etc for the limit-1 digits you select the value in control using ctrl+shift+left or right arrow key combination and press numeric key for new value, it is working fine, but when you select all digits( length limit) the new numeric key is not able to enter in numericupdown control due to handling event below image:

KeyDown event code snippet with issue

Hence, @ Hans Passant suggested type cast workaround is better to this problem.

Add this line in formload event or in InitializeComponent() method.

((TextBox)numericUpDown1.Controls\[1\]).MaxLength = 4;

For proper handling of 4 digits length limit in below code snippet:

KeyDown event code snippet with Solution

Thanks! Hans Passant

Upvotes: 0

ABCD
ABCD

Reputation: 907

Use

KeyUp

Event.

Or

((TextBox)numericUpDown1.Controls[1]).MaxLength = 2; // As Hans mentioned.

Upvotes: 1

Oli
Oli

Reputation: 840

Just a quick idea:

public class StrictNumericUpDown : NumericUpDown
{
    protected override void OnTextBoxTextChanged(object source, EventArgs e)
    {
        base.OnTextBoxTextChanged(source, e);
        if (Value > Maximum)
        {
            Value = Maximum;
        }
    }
}

Upvotes: 2

Dusty Lau
Dusty Lau

Reputation: 591

You can use the KeyDown event and validate the value when it fires.

Upvotes: 0

Related Questions