asp.net C# 检查多个 DropDownList 的值

asp.net C# check value of multiple DropDownList

我做了一个搜索按钮,它将显示从 sql 到 gridview 的数据,搜索按钮与包含两个值(是)和(否)的 DropDownList 连接,所以如果用户选择(是)它应该得到值等于(是)和相同的东西(否)的数据。这对我很好用我确实吃了一个分开的,但是如果我同时搜索两个 DropDownList 它给我第一个 DropDownList 正确但第二个错误,例如如果 DropDownList1 =“是”显示(是)值并且如果 DropDownList2 = "no" 显示 (no) 值,它将 return (yes) 用于它们两个,

这是我的代码:

 if (DropDownList_laptop.SelectedValue == "1")
    {
        // ... code here
   SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_lap = 'yes'";
    }
    else if (DropDownList_laptop.SelectedValue == "2")
    {
        // ... code here
   SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_lap = 'no'";
    }

    else if (DropDownList_pc.SelectedValue == "1")
    {
        // ... code here
   SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_pc = 'yes'";
    }
    else if (DropDownList_pc.SelectedValue == "2")
    {
        // ... code here
    SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_pc = 'no'";
    }

下拉代码:

<asp:DropDownList ID="DropDownList_laptop" runat="server" Height="29px" Width="70px">
                        <asp:listitem text="" value="0"></asp:listitem>
                        <asp:listitem text="yes" value="1"></asp:listitem>
                        <asp:listitem text="no" value="2"></asp:listitem>
                        </asp:DropDownList>

我认为这样的东西应该适合你:

    string command = "SELECT * FROM emp_table";
    
    if (DropDownList_laptop.SelectedValue == "1"){
        command += " WHERE inv_lap = 'yes'";
    }
    else if (DropDownList_laptop.SelectedValue == "2")
    {
        command += " WHERE inv_lap = 'no'";
    }

    if (DropDownList_pc.SelectedValue == "1")
    {
        command += " AND inv_pc = 'yes'";
    }
    else if (DropDownList_pc.SelectedValue == "2")
    {
        command += " AND inv_pc = 'no'";
    }
    
    SqlDataSource1.SelectCommand = command;

看后面的代码逻辑。您正在使用 if-elseif-elseif 等。这意味着满足的第一个条件将被触发,而任何进一步的条件子句都不会。因此,您想将与单独下拉列表相关的 if 条件分离到单独的 if 子句中。

if (DropDownList_laptop.SelectedValue == "1")
{
  SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_lap = 'yes'";
}
else if (DropDownList_laptop.SelectedValue == "2")
{
  SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_lap = 'no'";
}

// separate dropdown, separate logic!
if (DropDownList_pc.SelectedValue == "1")
{
  SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_pc = 'yes'";
}
else if (DropDownList_pc.SelectedValue == "2")
{
  SqlDataSource1.SelectCommand = "SELECT * FROM emp_table where inv_pc = 'no'";
}