【问题标题】:remove selected item from combobox in winform application从winform应用程序的组合框中删除选定的项目
【发布时间】:2014-04-17 09:46:09
【问题描述】:

我正在开发 Windows 窗体应用程序..

我有两个组合框..我将组合框 drop down style 属性更改为 DropDownList

保存数据后,我想清除组合框中的项目..所以我给出了这样的代码:

CmbDepartment.Text = "";
cmbvisitpurpose.Text = "";

但这并没有从我的组合框中清除所选项目..所以我更改了这样的代码:

cmbvisitpurpose.Items.RemoveAt(cmbvisitpurpose.SelectedIndex = -1)
CmbDepartment.Items.RemoveAt(CmbDepartment.SelectedIndex = -1)

这是从我的组合框中永久删除特定项目..如果我想获取组合框中的所有项目..我想加载页面..我只想清除所选项目.. 我该怎么做?

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    这只会从组合框中删除,而不是从数据源中删除。

    如果要保留项目,最好使用本地集合。

    CmbDepartment.Items.Remove(CmbDepartment.SelectedItem);
    

    这是一个关于如何将值分配给集合的示例

        List<string> DepartmentsPermanent;
        List<string> DepartmentsTemporary;
        public Form1()
        {
            InitializeComponent();
    
            DepartmentsPermanent = new List<string>();
            DepartmentsPermanent.Add("EEE");
            DepartmentsPermanent.Add("CSE");
            DepartmentsPermanent.Add("E&I");
            DepartmentsPermanent.Add("Mechanical");
            comboBox1.DataSource = DepartmentsPermanent;
            //here you assign the values to other List
            DepartmentsTemporary = DepartmentsPermanent.ToList();
    
    
        }
        //Now if you have selected EEE from the list and you want to remove on selection
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null && DepartmentsTemporary != null)
            {
                DepartmentsTemporary.Remove(comboBox1.SelectedItem.ToString());
                comboBox1.DataSource = DepartmentsTemporary;
    
            }
            //If you want to assign the default values again you can just assign the PermanentList
            //comboBox1.DataSource = DepartmentsPermanent;
        }
    

    【讨论】:

    • 没有收到任何错误..从我的组合框中删除的选定项目
    • 这就是你所要求的
    • 如果我使用 CmbDepartment.SelectedIndex = -1 然后就好了,但问题是我在组合框选择索引中有很多代码改变了,如果我给出的这个代码也可以工作,我不这次想要代码工作
    • 先生,在您的代码中选择的项目从组合框中永久删除
    • 那么你应该使用一个集合
    【解决方案2】:

    如果要清除选中项,应将ComboBox.SelectedIndex属性设置为-1

    http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindex%28v=vs.110%29.aspx

    【讨论】:

    • 先生,我的选择更改事件中有很多代码..如果我使用此代码,那么它将移动到选择索引更改代码,所以这次我可以如何防止移动它?
    猜你喜欢
    • 1970-01-01
    • 2015-04-08
    • 2018-05-24
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多