通过字符串参数传递条件where子句? (asp.net/c#)

问题描述 投票:-1回答:1
foreach (ListItem lst in chkPrice.Items)
{
    if (lst.Selected)
    {
        if (lst.Value == "1")
        {
            P = ">=1 AND <=2000";
        }
        if (lst.Value == "2")
        {
            P = "BETWEEN 2000 AND 5000";
        }
        if (lst.Value == "3")
        {
            P = "BETWEEN 5000 AND 8000";
        }
        if (lst.Value == "4")
        {
            P = "Greater Than 8000";
        }

        P = P + "," + P;
        PS = true;
    }


Query = "Select * from tbl_Product WHERE Product_SalePrice IN (" + P + ") ";
ViewProductCode(Query);


<asp:CheckBoxList ID="chkPrice" runat="server" OnCheckedChanged="CheckBox_CheckedChanged" AutoPostBack="true">
    <asp:ListItem Text="&nbsp;&nbsp;PKR 0 - PKR 2000" Value="1"></asp:ListItem>
    <asp:ListItem Text="&nbsp;&nbsp;PKR 2000 - PKR 5000" Value="2"></asp:ListItem>`enter code here`
    <asp:ListItem Text="&nbsp;&nbsp;PKR 5000 - PKR 8000" Value="3"></asp:ListItem>
    <asp:ListItem Text="&nbsp;&nbsp;PKR 8000 and above" Value="4"></asp:ListItem>
</asp:CheckBoxList>

应该如何在p字符串参数中写入条件以将其传递给查询?

c# asp.net conditional-statements checkboxlist
1个回答
0
投票

在复选框中,仅传递选择的项目。因此,您无需检查list.selected。而不是使用所有这些if语句,而是使用switch

p = '';
foreach (ListItem lst in chkPrice.Items)
{
    switch(lst.Value) {
        case "1":
            P += " >=1 AND <=2000,";
            break;
        case "2":
            P += " BETWEEN 2000 AND 5000,";
            break;
        case "3":
            P += " BETWEEN 5000 AND 8000,";
            break;
        case "4":
            P += " > 8000,";
            break;
        default:
            // define a default behavious
            break;
    }
    PS = true;
}

// delete the last comma(,)
P = P..Remove(P.Length - 1);

Query = "Select * from tbl_Product WHERE Product_SalePrice IN (" + P + ") ";
ViewProductCode(Query);
© www.soinside.com 2019 - 2024. All rights reserved.