0

I have one combobox in which I have set DataSource Value, but when I try to set SelectedValue, the ComboBox returns null. so please help.

BindingList<KeyValuePair<string, int>> m_items =
                     new BindingList<KeyValuePair<string, int>>();

for (int i = 2; i <= 12; i++)
    m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;

cboGridSize.SelectedValue = 4;

when I set SelectedValue with 4 then it returns NULL.

user3568411
  • 1
  • 1
  • 2

2 Answers2

0

Agree with @Laazo change to string.

cboGridSize.SelectedValue = "4";

or somthing similar to this

int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;

MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());

and refer to this looks as if it would be good for your issue:

0

I came across this question while also trying to solve this problem. I solved it by creating the following extension method.

        public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
    {
        // In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
        // that there will be an ID for the comparison.

        /* Enumerating over the combo box items is the only way to set the selected item.
         * We loop over the items until we find the item that matches. If we find a match,
         * we use the matched item's index to select the same item from the combo box.*/
        foreach (T item in cb.Items)
        {
            if (item.ID == id)
            {
                cb.SelectedIndex = cb.Items.IndexOf(item);
            }
        }
    }

I also created an interface called IDatabaseTableClass (probably not the best name). This interface has one property, int ID { get; set; } To ensure that we actually have an ID to compare to the int id from the parameter.

JasonG
  • 127
  • 1
  • 8