Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems with changing selected item in a combobox

Status
Not open for further replies.

taalmod

Programmer
Oct 15, 2008
2
0
0
DK
I am writing an application, where I fill a combobox with strings and then select a value.
Sometimes, I want to programmatically change to another value, but I cannot get that to work.
Assignments to .Text or .SelectedItem does not work, and even if I start with setting the selectedIndex = -1, it flips back to the old position when I try to set it to the new.

Anyone got any advice?

public void SetString(string name) {
int index = comboBoxtask.FindString(name);
comboBoxtask.SelectedIndex = -1; // this is ok
comboBoxtask.Text = ""; // is already empty, but what the heck
comboBoxtask.Text = name; // reverts back to the old name??
comboBoxtask.SelectedIndex = index; // no change, still old index now even though it is -1 before the text is set
comboBoxtask.SelectedItem = comboBoxtask.Items[index]; // does not work either
}
 
I can make it work, if I start by clearing the items, and then re-inserting them and selecting what I want, but it seems like a stupid solution to do that, just to change the selection.

Does anybody have a more elegant solution?

Brute force code that works:
public void SetString(string name) {
// be desperate and delete all the items anmd re-insert them
int index = comboBoxtask.FindStringExact(name);

comboBoxtask.Items.Clear();
comboBoxtask.SelectedIndex = -1;
comboBoxtask.Text = "";

SetPossibleTasks(possibletasks); insertion of items into the combobox


comboBoxtask.Text = name;
comboBoxtask.SelectedIndex = index;
if (index >= 0) {
comboBoxtask.SelectedItem = comboBoxtask.Items[index];
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top