在组合框中设置默认项目

Sri*_*ava 6 c# visual-studio winforms

我有一个在组合框中设置项目的功能,默认情况下会设置一个项目

- 选项列表 -

 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

有谁能建议这样做的方法?

Vex*_*exy 14

我重写了这个答案以澄清一些内容.

首先,必须将"默认"文本添加为​​组合项.的使用 combo.Text性质,只是增加的说明文字以组合框被"丢失"的第一次用户做一些与控制.如果您希望在组合中永久使用"默认"文本,则必须将其添加为组合框项目.

根据您提供的代码,只需修改

cmbOperations.Text = "-SELECT OPERATIONS-";
Run Code Online (Sandbox Code Playgroud)

cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-");
Run Code Online (Sandbox Code Playgroud)

请注意,这样您将项目添加"-SELECT OPERANDS-"到列表中的第0个(读取第一个)位置.还要确保所有后续项目都增加1,因为它们现在在列表中向下移动了一个空格.

最后,放

cboOperations.SelectedIndex = 0;
Run Code Online (Sandbox Code Playgroud)代码末尾的行.通过这样做,你告诉组合框在表单(或控件)加载时最初显示你的"默认"项.

还有一件事.我不是很确定你想达到与超过设定组合项目的代码是什么,但如果你想检查哪些用户选择使用cboOperations.SelectedIndex其中包含目前在组合选择的项目属性.你可以添加简单

if(cboOperations.SelectedIndex == someIntValue){...}
Run Code Online (Sandbox Code Playgroud) 其余的是你的程序逻辑;)