ASP.Net SQL查询Where子句中的动态列

时间:2018-01-09 11:32:06

标签: sql asp.net

我需要从控件的值中动态选择where子句中的列,有人可以帮忙。

我需要这方面的帮助:

SelectCommand="SELECT * FROM [Skills] WHERE (@YearCol = @YearValue)">

YearCol是一个下拉列表,我希望where子句中的列成为下拉列表中的选择。

这是我正在使用的完整代码。

<form id="form1" runat="server">
    <div>
    </div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem>Year1</asp:ListItem>
        <asp:ListItem>Year2</asp:ListItem>
        <asp:ListItem>Year3</asp:ListItem>
        <asp:ListItem>Year4</asp:ListItem>
        <asp:ListItem>Year5</asp:ListItem>
    </asp:DropDownList>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Skills] WHERE (@YearCol = @YearValue)">
        <SelectParameters>
            <asp:ControlParameter ControlID="DropDownList1" DefaultValue="Year1" Name="YearCol" PropertyName="SelectedValue" Type="String" />
            <asp:Parameter DefaultValue="1" Name="YearValue" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>
</form>

2 个答案:

答案 0 :(得分:2)

您应该手动更改它,因为参数仅用于col值而不是col name,因此请执行以下操作:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    string selectCommand = "SELECT * FROM [Skills] WHERE ({0} = @YearValue)";
    string yearParam = Convert.ToString(e.Command.Parameters["@YearCol"].Value);
    string yearColName = string.Empty;
    switch (yearParam)
    {
        case "Year1":
            yearColName = "Year1";//What you want
            break;
        case "Year2":
            yearColName = "Year2,Year3";
            break;
          .....
    }
    e.Command.Parameters["@YearValue"].Value = yearParam;
    SqlDataSource1.SelectCommand = string.Format(selectCommand, yearColName); 
}

可以在Selecting事件或ddl更改事件或您想要的位置完成。

答案 1 :(得分:0)

我接受Aria的回答,但也添加了我的最终代码,以防有人帮忙。我只需要将dropdownbox值作为where子句中的Column Name。仍然感到惊讶,ASP不支持它。

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
{
con.Open();
string selectCommand = "SELECT * FROM [Skills] WHERE ({0} = '1')";
String yearColName = Convert.ToString(DropDownList1.SelectedItem);
SqlDataSource1.SelectCommand = string.Format(selectCommand, yearColName);
}
}