繁体   English   中英

如何将DropDownList选择的值分配给SqlDataSource?

[英]How to assign DropDownList selected value to SqlDataSource?

我有一个从本地数据库获取数据的列表视图,并且有一个DropDownList可以按类型过滤asp:list视图中的项目。 我是用向导完成的。

在我将它们绑定之后。 它只能按过滤器显示项目。 但是,我不能同时显示所有项目。

所以我决定将它们自己绑定在后面的代码中,但我没有任何结果,这是我的下拉列表索引更改事件中的代码:

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

        }

如果使用SqlDataSource ,则最简单的方法是在前面绑定数据。

数据库

注意:我将TypeId创建为整数。

在此处输入图片说明

ASPX

如果DropDownList的选定值为-1 ,则SqlDataSource将返回所有项目。

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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