So i got this 5 drop downs i need to use for sorting output from sql
Now i use
DropDownList_Instruktorer.Items.Insert(0, new ListItem("Vælg Instruktør", "*"));
For the Default Value, and i was thinking this will do the job. But
cmd.Parameters.addwithvalue
enter the value into value obviously instead of use * to show all results like it normally does in sql
SqlCommand cmd = new SqlCommand(@"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE fk_in_id = @Instruktor AND
fk_st_id = @Stilart AND
fk_ag_id = @Aldersgruppe AND
fk_ni_id = @Niveau AND
fk_ht_id = @Tid", conn);
cmd.Parameters.AddWithValue("@Instruktor", DropDownList_Instruktorer.SelectedValue);
cmd.Parameters.AddWithValue("@Stilart", DropDownList_Stilart.SelectedValue);
cmd.Parameters.AddWithValue("@Aldersgruppe", DropDownList_Aldersgrupper.SelectedValue);
cmd.Parameters.AddWithValue("@Niveau", DropDownList_Niveauer.SelectedValue);
cmd.Parameters.AddWithValue("@Tid", DropDownList_Tider.SelectedValue);
Here is my sql, Any idea how i can i get it to work without writing 25 if statements?
Why not use a string in place of the AddWithValue, eg:
string instructorStr = "";
string stilartStr = "";
...
if (DropDownList_Instruktorer.SelectedValue != "*")
{
instructorStr = "fk_in_id = " + DropDownList_Instruktorer.SelectedValue + " AND";
}
if (DropDownList_Stilart.SelectedValue != "*")
{
stilartStr = "fk_st_id = " + DropDownList_Stilart.SelectedValue + " AND";
}
...
SqlCommand cmd = new SqlCommand(@"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE " +
instructorStr +
stilartStr +
...
+ " 1 = 1", conn);
Then you have the option to do all sorts of stuff with the individual variables, including ORDER BY
Using Stringbuilder would be cleaner but it's easier to show it this way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.