2

I have this list view that fetches data from local db, and there is a DropDownList to filter the items in asp:list view by their type. I did it with wizard.

After I bind them. it could only show items by filter. However, I could't show all items while I want both options.

So I decided to bind them myself in code behind, and I couldn't get any result here's my code in drop down list index changed event:

    protected void BookListddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (BookListddl.SelectedIndex == 0)
        {
            SqlDataSource dataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings[0].ConnectionString
            , "SELECT * FROM BookTbl");
            dataSource.SelectCommandType = SqlDataSourceCommandType.Text;
            dataSource.SelectCommand = "SELECT * FROM BookTbl";
            dataSource.DataBind();
            ListView1.DataSourceID = dataSource.ID;
            ListView1.DataBind();

        }
        else
        {
            SqlDataSource dataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings[0].ConnectionString
                , "SELECT * FROM [BookTbl] WHERE [TypeId] = '" + BookListddl.SelectedValue + "'");
            dataSource.SelectCommandType = SqlDataSourceCommandType.Text;
            dataSource.SelectCommand = "SELECT * FROM [BookTbl] WHERE [TypeId] = '" + BookListddl.SelectedValue + "'";
            dataSource.DataBind();
            ListView1.DataSourceID = dataSource.ID;
            ListView1.DataBind();

        }

1 Answer 1

3

If you use SqlDataSource, the easiest way will be to bind data at front.

DataBase

Note: I created TypeId as integer.

enter image description here

ASPX

If DropDownList's selected value is -1, SqlDataSource will return all items.

<asp:DropDownList ID="BookListddl" runat="server" AutoPostBack="True">
    <asp:ListItem Text="All" Value="-1" />
    <asp:ListItem Text="Fiction" Value="1" />
    <asp:ListItem Text="None Fiction" Value="2" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    SelectCommand="SELECT * FROM [BookTbl] WHERE [TypeId] = @TypeId OR @TypeId = -1">
    <SelectParameters>
        <asp:ControlParameter ControlID="BookListddl"
            PropertyName="SelectedValue"
            Name="TypeId"
            Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.