所以我得到了这5个下拉,我需要用来从sql
中排序输出现在我用
DropDownList_Instruktorer.Items.Insert(0, new ListItem("Vælg Instruktør", "*"));
对于默认值,我认为这将完成这项工作。但是
cmd.Parameters.addwithvalue
显然将值输入值而不是使用*来显示所有结果,就像通常在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);
这是我的sql,我知道如何在不编写25条if语句的情况下让它工作吗?
答案 0 :(得分:0)
为什么不使用字符串代替AddWithValue,例如:
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);
然后你可以选择用各个变量做各种各样的事情,包括ORDER BY
使用Stringbuilder会更干净,但更容易以这种方式显示它。