C# 检查是否选择了 ComboBox 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14322134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a ComboBox value is selected
提问by Idanis
I'm writing a form which includes some buttons and a combo box. The "Ok" button is disabled by default, and I wish to enable it only after an actual value (not the combo box's name) is selected.
我正在编写一个表单,其中包含一些按钮和一个组合框。“确定”按钮默认禁用,我希望仅在选择实际值(不是组合框的名称)后启用它。
I know how to access the selected value, and how to check if a value has been selected - but these two can be done only after the form is close (using the"x" or using the "ok" button - which is disabled).
我知道如何访问选定的值,以及如何检查值是否已被选择——但这两个只能在表单关闭后才能完成(使用“x”或使用“确定”按钮——这是禁用的) .
Any ideas?
有任何想法吗?
Thanks.
谢谢。
采纳答案by Mitch
Perhaps like this:
也许像这样:
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox.SelectedIndex > -1)
{
buttonOK.Enabled = true;
}
}
By default a combobox's selected index is -1 (the combobox's name, which you can't reselect after choosing another index), so if you check that it's not -1 then you know a value has been selected.
默认情况下,组合框的选定索引为 -1(组合框的名称,在选择另一个索引后无法重新选择),因此如果您检查它不是 -1,那么您就知道已选择了一个值。
However another alternative, and the one I use, is if I always want a value to be selected is to use the DropDownStyle
property and set it to DropDownList
. That way index 0 is selected by default and the user can only select items from the list and nothing else.
然而,另一种选择,也是我使用的,如果我总是想要选择一个值,则使用该DropDownStyle
属性并将其设置为DropDownList
. 这样,默认情况下选择索引 0,用户只能从列表中选择项目,而不能选择其他项目。
回答by rs.
You can use combobox selected index changed event
您可以使用组合框选择索引更改事件
Add this to your InitializeComboBox class
将此添加到您的 InitializeComboBox 类
this.ComboBox1.SelectedIndexChanged +=
new System.EventHandler(ComboBox1_SelectedIndexChanged);
then in selected index changed event you can check if combox box is selected
然后在选定的索引更改事件中,您可以检查是否选择了组合框
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cbx= (ComboBox) sender;
Button1.Enabled = !string.IsNullOrEmpty(cbx.SelectedItem.ToString());
}
回答by spajce
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
button1.Enabled = false;
else
button1.Enabled = true;
//or
//button1.Enabled = comboBox1.SelectedIndex == -1;
}