加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在组合框中设置默认项目

发布时间:2020-12-15 17:36:13 所属栏目:百科 来源:网络整理
导读:我有一个在组合框中设置项目的功能,默认情况下会设置一个项目 – 选项列表 – public void SetOperationDropDown() { int? cbSelectedValue = null; if(cmbOperations.Items.Count == 0) { //This is for adding four operations with value in operation dr
我有一个在组合框中设置项目的功能,默认情况下会设置一个项目

– 选项列表 –

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属性只是将组合描述性文本添加到组合框中,这是第一次用户对控件执行某些操作时“丢失”.
如果您希望在组合中永久使用“默认”文本,则必须将其添加为组合框项目.

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

cmbOperations.Text = "-SELECT OPERATIONS-";

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

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

最后,放

cboOperations.SelectedIndex = 0;

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

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

if(cboOperations.SelectedIndex == someIntValue){...}

其余的是你的程序逻辑;)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读