문제

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")));
    }
도움이 되었습니까?

해결책 2

I had to call ValidateChildren methods to trigger validation.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top