View Full Version : ListBox1.SelectedIndex

01-08-2007, 08:23 PM
Hi all -

I am having a problem with trying to get the selected index from my listbox. I want to remove a name from a listbox (as well as from my DB table) when I click a button. The problem is that the selected index is always -1 until after a postback. This is different than the behavior on a windows application form which will immediately give the selected index in the selectedindexchanged event.

I have tried redirecting to my same page on the button click to get the selected index value and then trying to call a sub in a certain event "after" the selected index has been set (i.e. LoadComplete, PreRenderComplete), but nothing is working out for me.

Any suggestions on how to get that selected index after clicking my "Remove" button?

01-08-2007, 09:36 PM
If we do a trace of your code step by step. First you populated your listbox on page_load and then the user select something in the listbox and click the button to delete the selected item but the problem is when the user click the button to delete, the page_load event occur before the button_click event so the selected item is no longer selected.

To fix the problem, make sure to populate your listbox only if no postback occur like below:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
'Code to populate your listbox here...
End If
End Sub

01-08-2007, 09:49 PM
Thank you. This did work. I put the source load of my listbox inside the suggested if statement. My button click now has the correct selected index value. I can then remove from my database table, do my refresh to the listbox, and all is good.

01-09-2007, 03:04 AM
You'r welcome :)