简体   繁体   中英

Disabling item in a ComboBox C#

I have found what seems to be an easy solution to disable certain items in a ComboBox in here . It states:

You can disable an item in a list box or combo box by adding a single backslash to the beginning of the expression.

However if I write

testBox.Items.Add("\Test item");

or

testBox.Items.Add(\"Test item");

it gives a syntax error in VS2010. Maybe this function has been disabled in later than 2005 versions?

If I put an item through a VS2010 designer like this

\Test item

or I write

testBox.Items.Add("\\Test item");

then it appears with a backslash and not is disabled.

Thus my question is: is this method somehow available and I just fail to understand how to use it or I do have to create a custom ComboBox to achieve my goal (in title)?

sadly is it not possible for the combobox control.

I would recommend to just remove the item from the combobox list instead of trying to disable it.

with one of those 3 ways:

// To remove item with index 0:
comboBox1.Items.RemoveAt(0);
// To remove currently selected item:
comboBox1.Items.Remove(comboBox1.SelectedItem);
// To remove "Tokyo" item:
comboBox1.Items.Remove("Tokyo");

If you absolutely need to disable items, you will need to create a custom combobox.

UPDATE 1: This does NOT work, but I'm leaving it as is so the comments below make sense.

UPDATE 2: To answer your question... After a bit of googling around I believe your only option to achieve this with WinForms is to create your own control as you suggested.

I suspect the rules for working with items that begin with multiple backslashes would apply to escape sequences too. How about:

testBox.Items.Add("\]Test Item");

I'm not able to test it out, but it looks like it should work.

In general: You need to escape the backslash by writing \\\\ . Otherwise the compiler tries to interprete \\T as an escape sequence (which does not exist). I guess the designer does this for you already, but you can always take a look in the generated source code ;)

About disabling combobox items: The documentation you linked seems to apply for ListBoxes, not ComboBoxes. Furthermore, it refers to VisualFox Pro, not Windows.Forms. So I guess this won't work ;)

According to this discussion , you will need to subclass the control and overrride its paint handlers.

But before doing that, I would simply remove (or not even add) those items you wish to disable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM