سؤال

I want to program an app where the user can enter a number in a NumericUpDown Control. There are some conditions to the number (e.g. range) that are determined in run time. To give feedback to the user I changed BackColor of NumericUpDown to red when at least one condition is not met. So far it works as i expect it to do.

Now i wanted to add a ToolTip to NumericUpDown to explain why the number was "wrong". When I use the event NumericUpDown_BackColorChanged to adjust the text, the event just won't "trigger". Why is that?

I guess it has to do with the composite character of NumericUpDown as Hans Passant has stated here and here. But I am not sure. TY for the help in advance.

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        if (numericUpDown1.Value == 42)
        {
            numericUpDown1.BackColor = Color.Red;
        }
        else
        {
            numericUpDown1.BackColor = System.Drawing.SystemColors.Window;
        }
    }

private void numericUpDown1_BackColorChanged(object sender, EventArgs e)
    {
        //something epic should happen
        //but somehow my program never reaches these lines :(
    }
هل كانت مفيدة؟

المحلول

I've confirmed that the NumericUpDown.BackColor property setter indeed does not call OnBackColorChanged (in .NET 4.0 at least).

I assume this happens because the BackColor property has been overriden in UpDownBase to also set the BackColor of the composited controls inside NumericUpDown and maybe someone forgot to call the base implementation (I'd love to hear from some of the WinForms gurus here).

What you can do is create a FixedNumericUpDown control that inherits from NumericUpDown and overrides the BackColor property as such:

public Color BackColor
{
    override set
    {
        base.BackColor = value;
        OnBackColorChanged(EventArgs.Empty);
    }
}

نصائح أخرى

Suggestion: You can do this by add a ErrorProvider in your by drag and drop from toolbox.

Replace your code as below:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    { 
        errorProvider1.Clear();

        if (numericUpDown1.Value == 42)
        {
            numericUpDown1.BackColor = Color.Red;
            errorProvider1.SetError(numericUpDown1, "Select another number");
        }
        else
        {
            numericUpDown1.BackColor = System.Drawing.SystemColors.Window;
        }
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top