Search code examples
asp.netdropdown

ASP .NET Dropdown not reflecting SelectedItem


I have an Asp:DropDownList like this:

                    <asp:DropDownList runat="server" ID="ReinsurerInput">
                    </asp:DropDownList>

Filled like this:

                'Fill dropdowns
                If dsReinsurers.Tables("Reinsurers").Rows.Count > 0 Then
                    For Each dr As DataRow In dsReinsurers.Tables("Reinsurers").Rows
                        ReinsurerInput.DataSource = dsReinsurers.Tables("Reinsurers")
                        ReinsurerInput.DataTextField = "ReinsurerName"
                        ReinsurerInput.DataValueField = "ReinsurerId"
                        ReinsurerInput.DataBind()
                    Next
                End If

Here is my dropdown: https://ibb.co/h9J4ssb

Here is the input object on the backend: https://ibb.co/ysd93t4

How do I make the object on the backend match what the view is doing?


Solution

  • What does the page load event look like that loads up the dropdown list?

    You need this in 99% of use cases this:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        If Not IsPostBack Then
    
            LoadGrid
            LoadCombo
    
        End If
    
    End Sub
    

    in other words, loading up of data like a gridview, or dropdown list?

    You need to ONLY load it on the first REAL page load (IsPostBack = false).

    If you don't do the above, then on any button click or anything that triggers a post-back (which is quite much every event stub), then re-loading the dropdown list each time means the users' selection each time will be re-set and lost.

    so, ONLY load up the data on first page load. it also means of course your page will load faster/better, since you not re-pulling the data again each time a user clicks on some button or whatever.

    So, keep in mind that page load will trigger each time a button or whatever is clicked on that page. and if this happens to be code that needs/wants/gets the dropdown list, then of course you can't (don't want) the code to load up the dropdown list to re-run each time, since as noted, it will re-set the selection made.

    It possible that you already have the "correct" if/then block with a test for isPostback as per above, but , if not, then place your "loading data" code inside of that page load in that

      if not is postback block.