tags:

views:

1960

answers:

5

I have a ListBox that when in focus, and when I have an item selected returns a valid SelectedIndex. If I have a valid SelectedIndex and I click on a TextBox on the same Forum, the SelectedIndex now becomes -1. However I want it to keep its SelectedIndex from changing. How would I go about doing this?

+2  A: 

Handle the SelectedIndexChanged event and save the selected value so that you can restore it when your control regains focus.

jeffm
+1  A: 

I haven't verified this in my apps but if the SelectedIndex property changes when the LB loses focus you probably have to handle that case yourself by caching the last selected index and resetting it when the control regains focus. You can do this in the containing form or you can do it in a class derived from ListBox.

You could even try setting the selected index as soon as you see it becomes -1. Not sure what would happen but I'd be curious to find out....

Edit: just tested it and like the other poster I can't reproduce it either. Must be something slightly different about your LB

Andrew Queisser
+2  A: 
PersistenceOfVision
TextBox has AutoPostBack = true set perhaps?
SoloBold
Perhaps but the tags indicate this is a C# .NET and my understanding is that there is no AutoPostBack property available in C# .NET for the TextBox.
PersistenceOfVision
+1  A: 

Are these controls in different dialogs, or maybe different tabs on a tabbed container? That's the only way I can think of that you would lose your SelectedIndex when changing focus. Otherwise, how would anybody e.g. click a button to take action on an item? You'd lose the selection when focus went to the button you're clicking...

Coderer
A: 

I had the same issue as original poster. I couldn't figure it out totally but it seems like when you have the listbox bound to an observable collection and the collection gets changed that the selected item loses the focus.

I hacked around the issue by saving the selected index in a variable and resetting it if the selected index was -1 (and it was valid to restore it)

Dimestore Cowboy