【问题标题】:Setting default item in combo box在组合框中设置默认项
【发布时间】:2010-12-03 05:14:24
【问题描述】:

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

--选择列表--

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

谁能建议一种方法来做到这一点?

【问题讨论】:

    标签: c# visual-studio winforms


    【解决方案1】:

    我重写了这个答案以澄清一些事情。

    首先,“默认”文本也必须添加为组合项。 combo.Text 属性的使用只是将描述性文本添加到组合框,这是用户首次使用控件执行操作时“丢失”的。 如果您想在组合中永久使用“默认”文本,则必须将其添加为组合框项。

    通过您提供的代码,只需修改

    cmbOperations.Text = "-SELECT OPERATIONS-";

    cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-");

    请注意,通过这种方式,您可以将项目 "-SELECT OPERANDS-" 添加到列表中的第 0 个(首先读取)位置。 还要确保所有以下项目都增加 1,因为它们现在在列表中向下移动了一个空格。

    最后放上

    代码末尾的
    cboOperations.SelectedIndex = 0;
    行。通过这样做,您告诉组合框在表单(或控件)加载时最初显示您的“默认”项。

    还有一件事。我不太确定除了设置组合项之外,您还想用代码实现什么,但如果您想检查用户选择的内容,请使用 cboOperations.SelectedIndex 属性,该属性包含组合中当前选定的项。你可以添加简单的

    if(cboOperations.SelectedIndex == someIntValue){...}
    剩下的就是你的程序逻辑;)

    【讨论】:

      猜你喜欢
      • 2014-02-14
      • 2011-10-11
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 2023-03-03
      • 2015-02-08
      • 2017-10-03
      相关资源
      最近更新 更多