I have a list box control:
The code behind resembles:
<
It looks to me like you are creating a new eventhandler on each page load. This might be causing the problem. Why not attach the eventhandler declaratively:
<asp:ListBox runat="server" id="lbox" autoPostBack="true" OnSelectedIndexChanged="lbox_SelectedIndexChanged" />
also, why not reference the control directly, instead of casting?
protected void lbox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = lbox.selectedIndex;
}
Have you thought about loading the data earlier - e.g. in OnInit event on the page/user control. This occurs before the postback data is loaded and thus before an on-change can be processed? I believe that should work - but you might want to turn off viewstate!
I dont know if it makes a difference or not, but i generally attach my controls to events on the front page rather than in the codebehind. In your example i would have done:
<asp:ListBox runat="server" id="lbox" autoPostBack="true" OnSelectedIndexChanged="lboxScorecard_SelectedIndexChanged" />
Other than that, i would verify that the ViewState is enabled. ViewState can be turned of at the control, page, & even site level.
The real issue here is order of events. When you databind in page_load you overwrite the posted data, thats why the selection is not set in the listbox. You can easily overcome this by moving the binding logic to Page_Init.
Works for me too. Does your foo() return the same values every time?
Just as a side note: if possible, you should really do your databinding in OnInit (every time, not just on GETs). If you do it before the call to base.OnInit(...), the contents of your listbox won't have to be serialized and deserialized to and from viewstate and sent across the wire to the client (yes, you will be hitting the database more, but you'll be hitting a system which is located on your local subnet, or even on the same machine. Moreover, the database will likely cache the result).
If you want to build high-performance websites, you need to take a close look at the way you use ViewState. I highly recommend this article: TRULY Understanding ViewState
if your listbox items are same then selected index will get set to 0.To rectify it, set different values to item.value
and let item.text
remains the same..then selected index will be displayed properly.