Question

I'm using ErrorProvider in windows forms for the first time.

I have a simple window with a single combo box on it with several items in it, including a blank selection by default. I also have a Next button at the bottom.

When I run the form and just click next with the combo box set to blank my validation doesn't trigger. Any ideas?

I've wired up the error provider as provided in documentation.

        // Favorite Color ComboBox 
        favoriteColorComboBox = new ComboBox();            
        favoriteColorComboBox.Items.AddRange(new object[] {"None","Red","Yellow" });
        favoriteColorComboBox.Validated += new EventHandler(favoriteColorComboBox_Validated);

        favoriteColorErrorProvider = new System.Windows.Forms.ErrorProvider();
        favoriteColorErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;

        _tableLayoutPanel1.Controls.Add(favoriteColorComboBox, 1, 1);
    }

    void favoriteColorComboBox_Validated(object sender, EventArgs e)
    {
        if (!IsColorValid())
        {
            // Set the error if the favorite color is not valid.
            favoriteColorErrorProvider.SetError(this.favoriteColorComboBox, "Must select a color.");
        }
        else
        {
            // Clear the error, if any, in the error provider.
            favoriteColorErrorProvider.SetError(this.favoriteColorComboBox, String.Empty);
        }
    }

    private bool IsColorValid()
    {
        // Determine whether the favorite color has a valid value. 
        return ((favoriteColorComboBox.SelectedItem != null) &&
            (!favoriteColorComboBox.SelectedItem.ToString().Equals("None")));
    }
Was it helpful?

Solution 2

I had to call ValidateChildren methods to trigger validation.

OTHER TIPS

I think you have no event at button click. Combobox validation occurs only when you select combo and move out of it. In your case you are not selecting the combo itself so no question of firing any event. Try this:

private void _buttonNext_Click(object sender, EventArgs e)
{
    favoriteColorComboBox_Validated(sender, e);
}

It will fire same validation what you want when Next button is clicked.

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top