DeadlyDagger
DeadlyDagger

Reputation: 609

How to assign DropDownList selected value to SqlDataSource?

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();

        }

Upvotes: 2

Views: 5743

Answers (1)

Win
Win

Reputation: 62260

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>

Upvotes: 3

Related Questions