13

I am trying to deselect (blank out) a number of combo-boxes in my windows forms application. In my application I have a Reset method that sets the SelectedIndex for each combo to -1. All of my combo-boxes are databound, i.e. each combo-box is populated using a datasource.

I have noticed that sometimes my Reset method works, i.e. it deselects the currently selected item and blanks the combo. However, other times it chooses the first item (SelectedIndex = 0) straight after I attempt to set it to -1. From a users point of view this looks like a bug as it doesn't always "clear" the form.

According to MSDN:

"To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item."

Does anyone know of a work around?

Many thanks

1

16 Answers 16

30

Use combination of the void and property

comboBox.ResetText();

 //to reset selected value
comboBox.SelectedIndex = -1;
2
  • For me ResetText() was enough. Is there a reason for setting SelectedIndex to -1?
    – C4d
    Commented Mar 30, 2016 at 10:29
  • yes there is a reason because if you use binding source with backgroundworker that updates the GUI after rendering so after binding will remove text without rest value for that you will need to use both
    – Hisham
    Commented Mar 30, 2016 at 11:01
8

Don't know if anyone is still interested in this, seeing as it's now 5 years later, but I found a very easy workaround. Totally non-intuitive (I only found it by looking at the reference source code), but trivial to implement:

ComboBox1.FormattingEnabled = True;

Yep, that's all there is to it!

If you're curious, you can peruse the source code to see what's going on. It appears that the root cause of the bug noted by @CuppM is the attempt to set the position in the data source:

if (!FormattingEnabled || SelectedIndex != -1) {
    this.DataManager.Position = this.SelectedIndex;
} 

I would guess that it should have simply been '&&' instead of '||' in the condition, as the code probably shouldn't be setting the Position to an invalid value regardless of the FormattingEnabled property.

In any case, it allows for a simple workaround. And since the default behavior if the 'Format' property is blank is a no-op, you don't have to change anything else. It just works. :-)

(I should note that I have only tried this with .NET 4.7, so I can't say whether it works for prior versions of the .NET Framework.)

2
  • 1
    You the MAN! This worked perfectly. Before, the first time I was setting SelectedItem = Nothing the ComboBox would position on the first item and then I had to do it again to obtain a no selection. Now works as it should. Amazing as you managed to go through the reference code.
    – qfactor77
    Commented Oct 2, 2018 at 19:35
  • 1
    This should be the accepted answer. It is even documented in this article on MSDN. learn.microsoft.com/en-us/dotnet/api/…). Thank you.
    – James Roes
    Commented Jul 7, 2020 at 20:36
3

You can try to set the Selected Value or Item to null (Nothing in VB)

I cant remember the behavior of throwing an exception. However, I do remember that I used to insert a value called -1, (None) to the combo-box after it was databounded usually through the databind events. I'd recommend get the data in a List and insert the new value to this list. Bind the combo to the List now.

4
  • 3
    SelectedItem, yes. However, if you set SelectedValue to null (and the ComboBox is data-bound) it will throw an exception. Commented May 3, 2012 at 7:57
  • 1
    Plus it not a good idea to bind to live data anyways. Always retrieve the data in a local List and bind to the List. Hope you are using LINQ.
    – DoomerDGR8
    Commented May 3, 2012 at 8:04
  • Setting it the SelectedValue did throw an exception, SelectedIndex=null worked, however on a particular combobox (drop down) I had to do this twice, which is rather odd. I am not sure why? ALso I am not using LINQ, my project has to be .net 2
    – bobbo
    Commented May 3, 2012 at 8:56
  • When you say twice, how do you mean? Like write the line twice, one after the other?
    – DoomerDGR8
    Commented May 3, 2012 at 12:50
1

Only the following code works for me, so try:

comboBox.ResetText();   //framework  4.0 
1

ComboBox1.SelectedItem = null;

1

For anyone still looking at this old post I wanted to add a note from what Hisham answer.
Make sure to clear your list after inserting his code.

comboBox.ResetText();

//to reset selected value
comboBox.SelectedIndex = -1;
comboBox.Items.Clear();
0

Try assigning null or String.Empty to the SelectedValue property.

0

If your target framework is 4.0 - here is the solution:

Install .Net Framework 4.5 (do not change target framework of your project, just install the framework). After installing, that line deselects databound combobox:

combobox.SelectedValue = 0;

My value member is "Id" int primary key auto-increment, so that field does not contain value 0. However, that won't work on Windows versions, that do not support .net45

0

Try to set the [ComboBoxObj].SelectedIndex=-1; which will make it to empty value. -1 refers to deselect or nullify the value of combobox

Thanks

0

I have had this problem for a while, but if you use:

'ComboBox.ResetText();'

it will make the text "" and leave the items in the combo box unaffected.

i used the following code in my application

 private void UpdateComboBox(ComboBox Box, string Group, List<string> Numbers)
        {
              Box.Items.Clear();
              Box.BeginUpdate();            
              Box.Items.Add("<<Add Contact>>");
              foreach (string item in Numbers)
              {
                   if(item != "")
                        Box.Items.Add(item);
              }
          Box.EndUpdate();
          Box.ResetText();
        }

So i run the method last, once all items are in the combo Box.

0

Try this line of code:

combobox1.Items.clear();

It works for me.

1
  • Please add some explanation to your answer such that others can learn from it
    – Nico Haase
    Commented Jul 17, 2020 at 7:22
0

When adding the datasource of the combobox before the main form was finished creating, setting the index to -1 did not work for me. The only thing that worked for me was first creating the controls and adding them to the form.

In the Form_load method last call a method that assigns the datasource of the comboboxes and sets the selectedindex to -1.

1
  • SO is english only site, all answer text should be in English, including comments in code. Variables or other names in other languages is generally OK.
    – moken
    Commented May 21, 2023 at 3:37
0
public void FillCmbo(String Sql, ComboBox cmb, String name, String id)
       {
           try
           {
               if (Con.State == ConnectionState.Open)
                   Con.Close();
               Con.Open();

               OleDbDataAdapter Ada = new OleDbDataAdapter(Sql, Con);
               DataTable Dte = new DataTable();
               Ada.Fill(Dte);
               DataRow Drw;
               Drw = Dte.NewRow();
               Drw.ItemArray = new object[] { 0, "<----Select---->" };
               Dte.Rows.InsertAt(Drw, 0);
               cmb.DisplayMember =name;
               cmb.ValueMember = id;
               cmb.DataSource = Dte;
           }
           catch (System.Exception ex)
           {

               MessageBox.Show(ex.Message, "Check", MessageBoxButtons.OK, MessageBoxIcon.Information);
           }
       }
-1

Add to your combobox one empty item, something like this:

cb.Items.Add("");

After this you can deselect your combobox by selecting the last cb item:

cb.SelectedIndex = cb.Items.Count - 1;

There you go!

You'll have the last place empty in your combobox, but it wont bother you. will it? :-)

-1

I got the following error:

There is no row at position 0

when I was setting ComboBox.SelectedItem to -1.

Replacing by ComboBox.ResetText() worked OK. This was using .Net 4.6.1, with VS 2013 where TextFormatting = True by default for ComboBoxes.

-3

you may try to use this solution..

dataGrid.DataSource = Nothing

dataGrid.DataBind()

hope its help!..:D

3
  • dataGrid ?? do you mean ComboBox ?
    – Habib
    Commented May 3, 2012 at 7:51
  • This is clearly tagged as C#, Not VB. Also, he said ComboBox, not DataGrid.
    – KidCode
    Commented Aug 6, 2014 at 13:09
  • dataGrid.DataSource = null dataGrid.DataBind()
    – Diogo Cid
    Commented Jun 18, 2015 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.