使用不可选项创建WinForms ComboBox

sym*_*tis 8 .net c# combobox winforms

如何使用不可选项创建组合框控件?例如,可以将下拉列表中的项目可视地划分为某些组或类别的组名或类别名称.

Axe*_*ger 13

您可以添加一个特殊类并使用所选项来确定是否选择了该项,而不是在组合框中添加字符串.

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

  • 不.在我的情况下,我使用DropDownList样式禁用ComboBox禁用texteditor. (2认同)