locked
Listbox dropdown SelectedIndex resets after postback RRS feed

  • Question

  • I have been struggling with a problem for days now, and searched for
    related problems and solutions but had no luck.
    
    I have two dropdown listboxes where the first is populated in page load
    and the second is populated based on the input in the first. The first
    dropdown is inside a  "If Not Page.IsPostBackThey" if loop. Both have
    autopostback set to true.
    
    The problem is that when the user makes a choice in the first dropdown
    an event is triggered that will populate the second dropdown. This
    works okay, I can acess the selectedindex inside the code behind so
    that the second dropdown gets populated.
    
    The problem is to retrieve the choice that is made in the second
    dropdown. I try to save the selctedItem.text or the selectedIndex but
    always this is set to 1.
    
    I have seen that a lot of other programmers have had this problem where
    the second dropdown gets binded a second time before the selected
    values could get retrieved. This could normally get resolved by putting
    the binding inside a if not page.ispostback loop, but not in this case
    where i can not bind the second drop down after a choice is made in the
    first dropdown.
    
    Im wondering if I have a bug somewhere. Have tried Enabling Viewstate
    to no luck.
    
    Im adding some code here, any help would be appreciated.
    
    
    -----
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
       If Not Page.IsPostBack Then
                GetMainResearchData()
                GetSubResearchData(0)
                lstMainCategory.Items.Insert(0, New ListItem("Please Select Main Category", "None"))
                lstMainCategory.SelectedIndex = 0
       End If
    End Sub
    
    Private Sub lstMainCategory_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstMainCategory.SelectedIndexChanged
            mainKey = lstMainCategory.SelectedIndex()
            GetSubResearchData(mainKey)
        End Sub
    
    Private Sub lstSubCategory_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSubCategory.SelectedIndexChanged
        subKey = lstSubCategory.SelectedIndex() ' HERE THE VALUE IS ALWAYS 1
        Session("subid") = subKey
    End Sub
    
    
    Private Sub GetMainResearchData()
            Dim sqlText As String = "SELECT main_category key, main_category_title FROM ntnu_main_category ORDER BY main_category_title" 
            Dim myCommand As SqlCommand = New SqlCommand(sqlText, myConnection)
    
            Try
                myConnection.Open()
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                lstMainCategory.DataSource = myDataReader
                lstMainCategory.DataBind()
    
            Catch myException As Exception
                Response.Write("Feilmelding " & myException.ToString())
            Finally
                If Not myDataReader Is Nothing Then
                    myDataReader.Close()
                    myConnection.Close()
                End If
            End Try
        End Sub
    
        Private Sub GetSubResearchData(ByVal mainCategory As Integer)
    
            Dim sqlText As String = "SELECT sub_category_key, sub_category_title FROM ntnu_sub_category WHERE ntnu_sub_category.sub_category_key = " & mainCategory & ""
            Dim myCommand As SqlCommand = New SqlCommand(sqlText, myConnection)
            Try
                myConnection.Open()
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                lstSubCategory.DataSource = myDataReader
                lstSubCategory.DataBind()
                lstSubCategory.Items.Insert(0, New ListItem("Please Select sub category", "None"))
                lstSubCategory.SelectedIndex = 0
    
            Catch myException As Exception
                Response.Write("Feilmelding " & myException.ToString())
            Finally
                If Not myDataReader Is Nothing Then
                    myDataReader.Close()
                    myConnection.Close()
                End If
            End Try
        End Sub
     
    Wednesday, April 19, 2006 10:32 AM

Answers

  • Found the soution here. I tried adding a primary
    key for each sub category and used these for the listbox values. Then I could easily retrieve the correct selectedIndex. It seemed that when all the sub categories that used the sub_category_key for the datavaluefield in the listbox had the same value (since this value represented a main category), then I actually had just one item from the dropdown's point of view. So then it was impossible to retrieve the selectedindex, strangely enough.
    Thursday, April 20, 2006 5:00 PM

All replies

  • Two things -

    In your data binding routines, set DataTextField (what should be displayed) and DataValueField (what should be considered the key value). For example, in you GetMainResearchData() routine, right before lstMainCategory.DataBind(), write the following:

    lstMainCategory.DataTextField = "main_category_title"

    lstMainCategory.DataValueField = "main_category_key"

    Next, in your event handlers for SelectedIndexChanged, read from the SelectedValue property of the dropdown lists, not SelectedIndex. I'm assuming you want the key value associated with the selection, rather than the ordinal position of the selected item. It's a string, but if you need an Integer, you can always parse it. Or, since you're just creating a new SQL statement from it, you can keep it a string (i.e., rewrite GetSubResearchData to accept a string and not an integer).

    mainKey = lstMainCategory.SelectedValue

    GetSubResearchData(mainKey)

     

    Wednesday, April 19, 2006 11:01 PM
  • Thanks for your reply but I already have accounted for text and value field in the aspx file, when i declared the listbox.

    The problem is NOT that i dont get the selected value from the first listbox like this example:

    mainKey = lstMainCategory.SelectedValue

    GetSubResearchData(mainKey)

    The problem is in the second dropdown listbox: When the event for selectedIndex_changed is called i try to retrieve the selectedIndex or selectedItem.Text but this always returns the first position in the listBox.

    So: subKey = lstSubCategory.SelectedIndex always returns 1

    Im guessing I must have a bug somewhere, but I think this is weird since the only place i call the bind method for the second dropdown is in the top one, so it shouldnt get initialized and reset before i could retrieve the selected value.

     

     

     

    Thursday, April 20, 2006 6:59 AM
  • Found the soution here. I tried adding a primary
    key for each sub category and used these for the listbox values. Then I could easily retrieve the correct selectedIndex. It seemed that when all the sub categories that used the sub_category_key for the datavaluefield in the listbox had the same value (since this value represented a main category), then I actually had just one item from the dropdown's point of view. So then it was impossible to retrieve the selectedindex, strangely enough.
    Thursday, April 20, 2006 5:00 PM