views:

569

answers:

4

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.

+1  A: 

You could derive a new ComboBox class and handle the selection yourself.

Sani Huttunen
+1  A: 

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;
            }
        };
    }
}
Obalix
This was my first thought as well. However you can still type the item text into the ComboBox and thereby selecting the unselectable item.
Sani Huttunen
No. In my case I use DropDownList style for ComboBox disabling texteditor.
symantis
Your code is very well and it help for me. But another question - how to disable not only selecting items in list but disable tracking non-selectable items by mouse.
symantis
IMHO, this is difficult to achieve without drawing the drop down box on your own.
Obalix
A: 

Have a look here on CodeProject for a readonly Combo Box, here's another article to make the readonly combo box 'decent' looking... Here's another that shows how to override the basic standard combo box to make it readonly as Sani suggested.

Hope this helps, Best regards, Tom.

tommieb75
A: 

Hi Dear

We unable to use below coding successfully.

Errors - Selectable , Text , Value

Plz help. Eagerly awaiting a reply.

new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=0},

Dinsa