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
2010-02-18 17:16:01
+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
2010-02-18 17:23:41
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
2010-02-18 17:45:38
No. In my case I use DropDownList style for ComboBox disabling texteditor.
symantis
2010-02-18 17:50:25
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
2010-02-18 17:55:07
IMHO, this is difficult to achieve without drawing the drop down box on your own.
Obalix
2010-02-18 18:27:47
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
2010-02-18 17:26:14
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
2010-04-26 12:21:56