views:

555

answers:

3

I have an UpdatePanel with two ListBoxes in them. What I want to happen is that when the page loads the first ListBox fills with some data. When the user selects and item the second ListBox should be populated with the pertinent data.

Here is what happens, the first ListBox is filled with data, the user selects an item and the SelectedIndexChanged event fires, but the selection gets cleared before method can see which item was selected?

<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
    <table class="listBoxTable">
     <thead>
      <tr>
       <th>
        Please select a magazine to add articles to.</th>
      </tr>
     </thead>
     <tr>
      <td>     
       <asp:ListBox ID="lbMagazines" runat="server" Height="300px" Width="250px" 
        onselectedindexchanged="lbMagazines_SelectedIndexChanged" DataTextField="Title" 
        DataValueField="Id" AutoPostBack="True">

       </asp:ListBox>
      </td>
      <td>     
       <asp:ListBox ID="lbIssues" runat="server" Height="300px" Width="250px" 
        Enabled="False" DataTextField="Title" DataValueField="Id">

       </asp:ListBox>
      </td>
     </tr>
    </table>
</ContentTemplate>
</asp:UpdatePanel>
+1  A: 

Based on the information provided, my initial thoughts are that you are repopulating lbMagazines on page load, so that by the time it gets to the event, the selecteditem/index is cleared.

achinda99
Wow, what a newbie mistake. I didn't think the Page_load event would fire on AJAX call backs. Thanks a bunch.
jhunter
Whats pretty neat is that next to everything runs as if its a postback, even though its an ajax call. However, only controls within the update panel will update (unless you use javascript).
achinda99
+1  A: 

If only the second listbox's contents needs to change then it would be more appropriate to put the first listbox outside the UpdatePanel and use triggers property:

<Triggers>
    <asp:AsyncPostBackTrigger ControlID="lbMagazines" EventName="OnSelectedIndexChanged" />
</Triggers>

This way only the second listbox will be updated when you perform your AJAX postback.

Darin Dimitrov
Is using triggers more efficient or having both controls in the content template? I was never really sure of that.
achinda99
Using triggers is more efficient because only the part of your page that is inside the UpdatePanel will get updated, so the less controls you have less inside the less data will be exchanged between the client and the server.
Darin Dimitrov
+2  A: 

Sounds like your initial list binding code isn't wrapped in a Page.IsPostBack.

If (!Page.IsPostBack)
{
    //List bind code
}

When that's the case the original list will keep rebinding like you're seeing.

Gavin Miller