Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jan 2007
    Posts
    117
    Thanks
    4
    Thanked 2 Times in 2 Posts

    ListBox1.SelectedIndex

    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?

  • #2
    Regular Coder
    Join Date
    May 2006
    Posts
    181
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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:
    Code:
    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

  • #3
    Regular Coder
    Join Date
    Jan 2007
    Posts
    117
    Thanks
    4
    Thanked 2 Times in 2 Posts

    Thumbs up ListBox1.SelectedIndex

    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.

  • #4
    Regular Coder
    Join Date
    May 2006
    Posts
    181
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You'r welcome


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •