Reputation: 11
I am a junior on C#. I have problem with Combobox. When I using SelectedItem is no working exactly, what I want. SelectedItem always return the last item in combobox, but when I using SelectedIndex is return correct result.
Example in combobox is 3 items: Admin, Moderation, Salesman. Is always return Salesman, when I using SelectedItem, even when I select Admin.
There is my code:
class ComboboxItem
class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
add items into combobox
private void AddItemIntoComboBoxGroup()
{
string query = "SELECT* FROM kites_mango.staff_group; ";
DBUtility data = new DBUtility();
List<string>[] list = data.Select(query);
if (list != null && list[0].Count() > 0)
{
ComboboxItem item = new ComboboxItem();
for (int i = 0; i < list[0].Count(); i++)
{
item.Value = list[0][i];
item.Text = (list[1][i] + " - " + list[0][i]);
CbBGroup.Items.Add(item);
}
}
}
get selected item
if (CbBGroup.SelectedItem != null)
{
MessageBox.Show(CbBGroup.SelectedIndex + "/" + CbBGroup.SelectedItem.ToString());
}
Upvotes: 0
Views: 1199
Reputation: 651
You're instancing the ComboboxItem object before the for loop. This way, for each loop in your for statement, you're changing the properties of the same object, making objects that were loaded before in the list are also modified. That is, your list could have 3 itens, but they are going to have the same value (Salesman) because all the itens in your list have the same object reference.
Just change from this:
ComboboxItem item = new ComboboxItem();
for (int i = 0; i < list[0].Count(); i++)
{
item.Value = list[0][i];
item.Text = (list[1][i] + " - " + list[0][i]);
CbBGroup.Items.Add(item);
}
To this:
for (int i = 0; i < list[0].Count(); i++)
{
ComboboxItem item = new ComboboxItem();
item.Value = list[0][i];
item.Text = (list[1][i] + " - " + list[0][i]);
CbBGroup.Items.Add(item);
}
Upvotes: 1