Search code examples
c#asp.netdropdown

asp.net C# check value of multiple DropDownList


I made a search button that will show data from sql to gridview, the search button is connected with DropDownList that contain two values (yes)and(no), so if user selected (yes) it should get the data where the value equals (yes) and the same thing with (no). this works with me fine I do eatch one seperated, but if I searched for both DropDownList at once it give me the first DropDownList right but the second one wrong, for example if DropDownList1 = "yes" show (yes) value and if DropDownList2 = "no" show (no) value, it will return (yes) for both of them,

here is my code:

 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'";
    }

dropdown code:

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

Solution

  • I think something like this should work for you:

        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;