创建的WinForms组合框与非可选项目 [英] Create WinForms ComboBox with non-selectable items

查看:169
本文介绍了创建的WinForms组合框与非可选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建ComboBox控件与非可选项目?例如,这样的组名或CATEGORYNAMES直观地划分在DropDownList的物品进入某些群体或类别。

How to create combobox control with non-selectable items? For example, such groupnames or categorynames which visually divide items in dropdownlist into some groups or categories.

推荐答案

您可以添加一个特殊的类,并使用所选项目确定是否该项目被选中或不。

Instead of adding strings to your combobox you could add a special class and use selected item to determine whether the item is selected or not.

public partial class Form1 : Form
{
    private class ComboBoxItem
    {
        public int Value { get; set; }
        public string Text { get; set; }
        public bool Selectable { get; set; }
    }

    public Form1() {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {
        this.comboBox1.ValueMember = "Value";
        this.comboBox1.DisplayMember = "Text";
        this.comboBox1.Items.AddRange(new[] {
            new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=0},
            new ComboBoxItem() { Selectable = true, Text="Selectable1", Value=1},
            new ComboBoxItem() { Selectable = true, Text="Selectable2", Value=2},
            new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3},
            new ComboBoxItem() { Selectable = true, Text="Selectable3", Value=4},
            new ComboBoxItem() { Selectable = true, Text="Selectable4", Value=5},
        });

        this.comboBox1.SelectedIndexChanged += (cbSender, cbe) => {
            var cb = cbSender as ComboBox;

            if (cb.SelectedItem != null && cb.SelectedItem is ComboBoxItem && ((ComboBoxItem) cb.SelectedItem).Selectable == false) {
                // deselect item
                cb.SelectedIndex = -1;
            }
        };
    }
}

这篇关于创建的WinForms组合框与非可选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆