I see you've already solved this, but why not do it the tried and tested way?
lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");
listBoxBeltPrinters.SelectedIndex = -1;
if (!String.IsNullOrEmpty(lblSelectedPrinter.Text)) {
for (int index = 0; index < listBoxBeltPrinters.Items.Count; index++) {
string item = listBoxBeltPrinters.Items[index].ToString();
if (lblSelectedPrinter.Text == item) {
listBoxBeltPrinters.SelectedItem = index;
break;
}
}
}
This way, you know the SelectedIndex
value is set to -1 as soon as the text changes, and if it is found in your ListBox
, that item is selected.
Even better would be to write a handler when the Label control lblSelectedPrinter
fires the TextChanged
event.
lblSelectedPrinter.TextChanged += new EventHandler(SelectedPrinter_TextChanged);
Then, create that Event Handler like shown above:
private void SelectedPrinter_TextChanged(object sender, EventArgs e) {
listBoxBeltPrinters.SelectedIndex = -1;
if (!String.IsNullOrEmpty(lblSelectedPrinter.Text)) {
for (int index = 0; index < listBoxBeltPrinters.Items.Count; index++) {
string item = listBoxBeltPrinters.Items[index].ToString();
if (lblSelectedPrinter.Text == item) {
listBoxBeltPrinters.SelectedItem = index;
break;
}
}
}
}
You've already solved your problem, so this is just food for thought.