Freigeben über


Did you know? To use the SQL select command based on a value selected from a dropdown list

Background:

I was looking for a requirement where I needed to use the SQL SELECT command based on a user’s input. In my case, it was a selection made from a DropDownList. This select command will be further used to populate a GridView.

The HTML code is as follows,

<asp:DropDownList ID=" DropDownList1" runat="server">

<asp:ListItem Selected="True">Select a Value..</asp:ListItem>

<asp:ListItem>Value 1</asp:ListItem>

<asp:ListItem>Value 2</asp:ListItem>

<asp:ListItem>Value 3</asp:ListItem>

</asp:DropDownList>

<br/>

<asp:Button ID="TextBox1" runat="server" Text="Search" onclick="TextBox1_Click" />

           

<asp:GridView ID=" GridView1" runat="server" />

          

Goal:

To write a SQL command that will select the values from the database based on the input provided in the DropDownList and further populate the GridView.

Solution:

This can be achieved using “ (double quotes) and the + symbol within single quotes as follows,

//Get connection string from Web.Config or declare a SqlConnection

String strConnection = ConfigurationSettings.AppSettings["myConnectionString"];

SqlConnection sqlConn = new SqlConnection(strConnection);

SqlCommand sqlCmd = new SqlCommand("SELECT Field1, Field2 FROM myTable where Field3 = '" + DropDownList1.SelectedValue.ToString() + "' ", sqlConn);

//Populating the Grid View – The code follows below..

 

I hope this helps.