Search code examples
asp.netvb.netentity-frameworklistviewdropdownlistfor

How do you filter an ASP.NET Entity Framework Bound ListView via DropDownList?


I am having some trouble figuring out the best way to filter an Entity Framework Query with the results of a DropDownList's Selected Value to fill a ListView Control.

My code is as follows:

Public Function ListViewProducts_GetData() As IQueryable

    Dim strVendorName As String = ddlFilterVendor.SelectedValue

    Dim myEntities As New InventoryProductsEntities()
    Return (From product In myEntities.InventoryProducts
           Order By product.ID Ascending
           Where product.VendorID = strVendorName
           Select product).Take(ddlDisplayRecords.SelectedValue)

End Function

This is pretty rough right now, but I would like to be able to filter this data by vendor, and then page it, but I cannot get the ListView to display the updated queried data. It just continues to display the same data as before, even with a ddlFilterVendor.SelectedValue change.

The drop down list code is as follows:

<asp:DropDownList ID="ddlFilterVendor" runat="server" AutoPostBack="True" DataSourceID="SqlDataSourceVendor" DataTextField="VendorID" DataValueField="VendorID" AppendDataBoundItems="True">
    <asp:ListItem Selected="True">All</asp:ListItem>
</asp:DropDownList>

I am stuck at this point.... I was thinking about posting the ddlFilterVendor.SelectedValue to the QueryString and reloading the page, but I would imagine that there should be an easier way to do this. Any help or ideas would be greatly appreciated! Thanks!

The SqlDataSource Code is as follows:

<asp:SqlDataSource ID="SqlDataSourceVendor" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT DISTINCT [VendorID] FROM [InventoryProducts]"></asp:SqlDataSource>

Solution

  • I have found a solution to this problem. In the DropDownList's SelectedIndexChanged event, I called the following method:

    ListViewProducts.DataBind()
    

    This re-queried the database with the appropriate Vendor filter, as shown in code snippet:

    Public Function ListViewProducts_GetData() As IQueryable
    
        Dim strVendorName As String = ddlFilterVendor.SelectedValue
    
        Dim myEntities As New InventoryProductsEntities()
        Return (From product In myEntities.InventoryProducts
                Order By product.ID Ascending
                Where product.VendorID = strVendorName
                Select product).Take(ddlDisplayRecords.SelectedValue)
    
    End Function
    

    Thanks!