简体   繁体   中英

Draw border for NumericUpDown

I have an user form in application. Some fields are validated. If field has wrong value red border is drawn for this control. It is made by handling Paint event for this control. I extended TextField and DateTimePicker to get Paint event from those classes objects. I have problem with NumericUpDown class. It does fire Paint event properly but invoking

ControlPaint.DrawBorder(e.Graphics, eClipRectangle, Color.Red, ButtonBorderStyle.Solid);

does completely nothing. Any ideas or suggestions? If I won't find any way to do it, I will add a panel to hold NumericUpDown control and I will be changing its background colour.

Each time handler is hooked up to Paint event I call control.Invalidate() to get it repainted.

Try this:

public class NumericUpDownEx : NumericUpDown
{
    bool isValid = true;
    int[] validValues = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (!isValid)
        {
            ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
        }
    }

    protected override void OnValueChanged(System.EventArgs e)
    {
        base.OnValueChanged(e);

        isValid = validValues.Contains((int)this.Value);
        this.Invalidate();
    }
}

Assuming your values are type int and not decimal. Your validity checking will probably be different but this worked for me. It draws a red border around the entire NumbericUpDown if the new value is not in the defined valid values.

The trick is to make sure you do the border painting after calling base.OnPaint. Otherwise the border will get drawn over. It may be better to inherit from NumericUpDown rather than assigning to its paint event because overriding the OnPaint method gives you complete control on the order of painting.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM