I am new to c#.
I’m currently working on a search function in asp.net with c# using three DropDownLists and a submit button. Let’s say, it’s a car website.
There are 2 DropDownLists:
- Make (for example – Toyota, Nissan, Honda . . .)
- Model (for example – Prius, X-trail, Insight . . )
If user choose only the first one (for example – he/she choose ‘Toyota’ and doesn’t choose other)and click submit, it will show all Toyota cars from the database. If user choose both ‘Make’ and ‘Model’, it will narrow the search.
If user doesn’t choose all dropdownlists, how should I write sql query for that and what if user choose all.
And the items of dropdownlists are directly added from the database. I also don’t know how to set the default value text at the top of the dropdownlist.
con.Open();
if (!IsPostBack)
{
cmd = new SqlCommand("SELECT DISTINCT CarMake FROM Car", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
}
Especially when building SQL from a public webform like this you should (I would say MUST) build your queries using parameters, not string concatenation. Otherwise it is a SQL injection attack waiting to happen.
One simple way to handle multiple filter possibilities is to use the
Likeoperator in the base SQL command. If either make or model is not chosen, just include a wild card instead of a make or model name: