Reputation: 93
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.
Upvotes: 9
Views: 25071
Reputation: 34592
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.
Upvotes: 0
Reputation: 16926
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;
}
};
}
}
Upvotes: 13