【问题标题】:How to assign DropDownList selected value to SqlDataSource?如何将 DropDownList 选定值分配给 SqlDataSource?
【发布时间】:2014-02-10 17:26:42
【问题描述】:

我有这个从本地数据库中获取数据的列表视图,并且有一个 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();

        }

【问题讨论】:

    标签: c# asp.net sql-server-2008


    【解决方案1】:

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

    数据库

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

    ASPX

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

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

    【讨论】:

    • 完美的解决方案,如果我能给你超过一分的话。
    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多