简体   繁体   中英

Sorting Listview

I have A listview which I want to sort. My problem is that when I click the sorting column the Onsorting event only fires when I Bind the data on pageload again. This means that on every pageload I will first have to bind the data, then I can catch the OnBinding event and after that I can Rebind the data again. Is there a better way to do this. Basically what I want is to bind the data only in the onsorting event

<asp:ListView ID="TempList" runat="server" OnSorting="TempList_sorting">
    <LayoutTemplate>
        <table >
            <tr>
                <th >
                    <asp:LinkButton runat="server" ID="btnSortVoorletters2" CommandName="Sort" Text="Voorletters"
                        CommandArgument="Voorletters" OnClick="btnSortVoorletters_Click" />
                </th>
            </tr>
              <tr runat="server" id="itemPlaceholder">
            </tr>
        </table>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <asp:Label ID="EmpIDLabel" runat="server" Text='<%# Eval("Naam") %>'/>
            </td>
        </tr>
    </ItemTemplate>
    <EmptyDataTemplate> 
    <p>Empty text that will be displayed.</p> 
</EmptyDataTemplate>

It lloks that you're always binding in PageLoad so that the previously supplied order is lost. Bind only if IsPostback is false. (You need to have the ListView EnableViewState set to true, which is the default value).

 if(!IsPostback)
 {
   // do the binding
 }

When the user clicks the 'Sort' button, the event will be fired and your event will sort and bind the data accordingly.

If the page is reloaded, and you don't rebind it in PageLoad this will be enough.

However, if for some reason you really need to rebind in PageLoad , what you have to do is to store the sorting in ViewState , a HiddenField or Session so that you can get the value from there to sort the data before binding it in PageLoad .

You should take the code that sorts and binds to a new method, and call it from both the Sort and the PageLoad events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM