1
votes

Could someone please explain how I could select programatically an item in the ComboBox when the item is defined like this:

    class ComboboxItem
    {
        public string DisplayString;
        public string Key;

        public ComboboxItem(string key, string displayString)
        {
            Key = key;
            DisplayString = displayString;
        }

        // Generates the text shown in the combo box
        public override string ToString()
        {
            return DisplayString;
        }
    }

The combo box gets populated with items at runtime like this:

myCombo.Items.Add(new ComboboxItem(“<key>“, “<text_to_display>”));

I need to select an item programatically based on the key but I cannot use the suggestion made here: Set the selecteditem of a combobox based on key,value pair. because I don't have foreknowledge of the data items as the ComboBox gets populated at runtime. Could someone please help? Many thanks.

EDIT - this is a winforms app.

2
I do have to ask why you are using that class at all. It doesn't seem to introduce any benefits over using just strings, and it makes certain things (like your current problem) much more complicated.Abion47
What kind of application is this? I mean winforms wpf or web?sujith karivelil
Quite frankly, I'm still somewhat new to c# and I don't know a better implementation. Can you please make a suggestion of a better way to add items that have a key as a 3-character code and a text description. When the user uploads a certain XML file, I extract the 3 character code from the XML data and then I need to pre-select the respective item in the combobox. Many thanks.user2430797
It is a winforms app, sorry I forgot to mention that.user2430797

2 Answers

3
votes

Try something like this

comboBox1.Items.Add(new ComboboxItem("a", "a"));
            comboBox1.Items.Add(new ComboboxItem("b", "b"));
            comboBox1.Items.Add(new ComboboxItem("c", "c"));
            comboBox1.Items.Add(new ComboboxItem("d", "d"));

            var key = "c";

            foreach (var item in comboBox1.Items)
            {
                var comboItem = (ComboboxItem) item;
                if (comboItem.Key.Equals(key))
                    comboBox1.SelectedItem = comboItem;
            }

I have just made a Winforms project and it worked. The combobox showed the "c" as selected value

You could use linq also. This could be a method to select your item

public void SelectItem(string key)
        {
            var comboItem = comboBox1.Items
                .Cast<ComboboxItem>()
                .FirstOrDefault(item => item.Key.Equals(key));
            if (comboItem == null)
            {
                //do whatever you want
            }
            else
            {
                comboBox1.SelectedItem = comboItem;
            }
        }

Hope it helps

1
votes

When looking at your code, one thing that is not really an issue as much as having to re-invent the wheel. Your ComboboxItem class looks suspiciously like a Dictionary, so it seems unnecessary to reinvent this class with your ComboboxItem class.

Another issue is your comment…

I need to select an item programatically based on the key but I cannot use the suggestion made here: Set the selecteditem of a combobox based on key,value pair. because I don't have foreknowledge of the data items as the ComboBox gets populated at runtime.

If this is true, then how could you possibly know what to select?

The code below used a Dictionary, ComboBox, Textbox and Button. The Dictionary is populated with some data and is then set to the ComboBox’s DataSource. Only the Text is displayed in the ComboBox. On the form the TextBox is used to allow the user to type in a value to change the ComboBox’s selected value to when the Button is clicked. If that key does not exist in the Dictionary then a message is display indicating the index was not found.

Since you say you do not know exactly what you may be looking for, I am curious how you expect to select the proper index. Hope this makes sence.

Dictionary<int, string> comboBoxData = new Dictionary<int, string>(); 
public Form1() {

  InitializeComponent();
  comboBoxData = GetDataDictionary();
  comboBox1.DataSource = new BindingSource(comboBoxData, null);
  comboBox1.DisplayMember = "Value";
  comboBox1.ValueMember = "Key";
}

private void SetSelectedIndex(int indexToSelect) {
  if (comboBoxData.Keys.Contains(indexToSelect)) {
    comboBox1.SelectedIndex = indexToSelect;
  }
  else {
    MessageBox.Show("The supplied key does not exist!");
  }
}

private Dictionary<int, string> GetDataDictionary() {
  Dictionary<int, string> dictionary = new Dictionary<int, string>();
  for (int i = 0; i < 15; i++) {
    dictionary.Add(i, "Item name " + i);
  }
  return dictionary;
}

private void buttonSelectIndex_Click(object sender, EventArgs e) {
  if (tbIndexToSelect.Text != "") {
    int indexToSelect = comboBox1.SelectedIndex;
    if (int.TryParse(tbIndexToSelect.Text, out indexToSelect)) {
      SetSelectedIndex(indexToSelect);
    }
  }
}