views:

149

answers:

2

Is there a way to make some of the items in a ListBox readonly/disabled so they can't be selected? Or are there any similar controls to ListBox to provide this functionality?

A: 

You can do this by overriding the OnDrawItem method and adding the code for drawing items in disabled state. You can find more information about this topic here Disabled ListBox:

Also there is a 3-rd party control, IntegralUI ListBox, where items are disabled simply by using the Enabled property:

item.Enabled = false;

However, this control is not free.

Lokey
+1  A: 

ListBox doesn't have support for that. You can bolt something on, you could deselect a selected item. Here's a silly example that prevents even-numbered items from being selected:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
  for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; ix--) {
    if (listBox1.SelectedIndices[ix] % 2 != 0) 
      listBox1.SelectedIndices.Remove(listBox1.SelectedIndices[ix]);
  }
}

But the flicker is quite noticeable and it messes up keyboard navigation. You can get better results by using CheckedListBox, you can prevent the user from checking the box for an item:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  if (e.Index % 2 != 0) e.NewValue = CheckState.Unchecked;
}

But now you cannot override drawing to make it look obvious to the user that the item isn't selectable. No great solutions here, it is far simpler to just not display items in the box that shouldn't be selectable.

Hans Passant