How to add an item to ComboBoxEdit?

2019-04-02 10:03发布

问题:

I have a small problem with ComboBoxEdit (DevExpress.XtraEditors). I cannot add a value or set SelectedIndex for my ComboBoxExit.

 ComboBoxEdit combo = new ComboBoxEdit();
 ComboBoxItemCollection coll = combo.Properties.Items;

 coll.BeginUpdate();

 try 
 {
    coll.Add(new PersonInfo("Sven", "Petersen"));
    coll.Add(new PersonInfo("Cheryl", "Saylor"));
    coll.Add(new PersonInfo("Dirk", "Luchte"));
 }
 finally 
 {
    coll.EndUpdate();
 }

 combo.SelectedIndex = -1; Comboboxedit1.Properties.Items.Add(combo);

It does not work and just adds shows this:

回答1:

WIth this line :

Comboboxedit1.Properties.Items.Add(combo);

You are adding the ComboBox object inside itself. ComboBoxEdit ToString() method returns the name you are seeing in your screenshot.

So, remove this line.

Your code in taken from the official DevExpress documentation (except the line above that you should remove), and works fine : items are indeed added.

However, setting the SelectedIndex property to -1 doesn't select anything, as the documentation states :

The BaseListBoxControl.SelectedIndex property is set to -1 for demonstrative purposes (the property is set to -1 by default). This ensures that no item is currently selected in the combo box.

You can do :

combo.SelectedIndex = 0;  // Select Sven

Or

combo.SelectedIndex = 1;  // Select Cheryl

Or

combo.SelectedIndex = 2;  // Select Dirk


回答2:

Use some like this:

try
{
    ComboBoxEdit combo = new ComboBoxEdit();

    combo.Properties.Items.Add("Sven, Petersen");
    combo.Properties.Items.Add("Cheryl, Saylor");
    combo.Properties.Items.Add("Dirk, Luchte");
}

Will work fine! No complication, no inovation, simple like need be!