combo box not validating

偶尔善良 提交于 2019-12-12 01:19:51

问题


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")));
    }

回答1:


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.




回答2:


I had to call ValidateChildren methods to trigger validation.



来源:https://stackoverflow.com/questions/13938073/combo-box-not-validating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!