在combobox中设置默认项目
我有一个在combobox中设置项目的function,默认情况下会设置一个项目
– 选项列表 –
public void SetOperationDropDown() { int? cbSelectedValue = null; if(cmbOperations.Items.Count == 0) { //This is for adding four operations with value in operation dropdown cmbOperations.Items.Insert(0, "PrimaryKeyTables"); cmbOperations.Items.Insert(1, "NonPrimaryKeyTables"); cmbOperations.Items.Insert(2, "ForeignKeyTables"); cmbOperations.Items.Insert(3, "NonForeignKeyTables"); cmbOperations.Items.Insert(4, "UPPERCASEDTables"); cmbOperations.Items.Insert(5, "lowercasedtables"); //ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-. cmbOperations.Text = "-SELECT OPERATIONS-"; } else { if(!string.IsNullOrEmpty("cmbOperations.SelectedValue")) { cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue); } } //Load the combo box cmbOperations again if(cbSelectedValue != null) { cmbOperations.SelectedValue = cbSelectedValue.ToString(); } }
有谁能建议这样做的方法?
我重写了这个答案以澄清一些内容。
首先,必须将“默认”文本添加为组合项。 使用combo.Text
属性只是将组合描述性文本添加到combobox中,这是第一次用户使用控件执行操作时“丢失”。 如果您希望在组合中永久使用“默认”文本,则必须将其添加为combobox项目。
根据您提供的代码,只需修改
cmbOperations.Text = "-SELECT OPERATIONS-";
至
cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-");
请注意,这样您将项目"-SELECT OPERANDS-"
添加到列表中的第0个(读取第一个)位置。 还要确保所有后续项目都增加1,因为它们现在在列表中向下移动了一个空格。
最后,放
cboOperations.SelectedIndex = 0;
代码末尾的行。 通过这样做,你告诉combobox在表单(或控件)加载时最初显示你的“默认”项。
还有一件事。 我不确定除了设置组合项之外你想要用代码实现什么,但是如果你想检查用户选择了什么用cboOperations.SelectedIndex
属性,其中包含当前所选项目的组合。 你可以添加简单
if(cboOperations.SelectedIndex == someIntValue){...}
剩下的就是你的程序逻辑;)