我正在爲自己的時間構建一個註冊類型的web應用程序,並且我想出了一點麻煩。基於多個複選框的Gridview過濾器
基本上我想讓Gridview根據選擇的複選框來改變它顯示的內容。到目前爲止,我已經有了很多工作,但現在當我嘗試讓它根據多個選擇進行篩選時,它會拋出關於WHERE語句的錯誤。現在我知道實際的問題是我只是絞盡腦汁想出解決方案。
我非常希望位置&類型檢查,一起做,但似乎foreach語句犯規像OR運營商吧..
感謝所有幫助
HTML代碼:
<div class="row">
<div class="col">
<asp:Label ID="Label1" runat="server" style="font-weight: 700" Text="Location"></asp:Label>
<asp:CheckBoxList ID="chklocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Location_Selected">
<asp:ListItem Text="Sydney" Value="Sydney"></asp:ListItem>
<asp:ListItem Text="Melbourne" Value="Melbourne"></asp:ListItem>
<asp:ListItem Text="Canberra" Value="Canberra"></asp:ListItem>
<asp:ListItem Text="Darwin" Value="Darwin"></asp:ListItem>
<asp:ListItem Text="Perth" Value="Perth"></asp:ListItem>
</asp:CheckBoxList>
</div>
<div class="col">
<asp:Label ID="Label2" runat="server" style="font-weight: 700" Text="Type"></asp:Label>
<asp:CheckBoxList ID="chktype" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Type_Selected">
<asp:ListItem Text="Desktop" Value="Desktop"></asp:ListItem>
<asp:ListItem Text="Laptop" Value="Laptop"></asp:ListItem>
</asp:CheckBoxList>
</div>
</div>
代碼隱藏:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string VDIListConnectionString = ConfigurationManager.ConnectionStrings["VDIListConnectionString"].ConnectionString;
string query = "SELECT UserName, Location, Type, Active, ImageNumber FROM VDI";
string condition = string.Empty;
foreach (ListItem item in chklocation.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" WHERE Location IN ({0}) AND Type IN ({0})", condition.Substring(0, condition.Length - 1));
}
foreach (ListItem item in chktype.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" WHERE Type IN ({0} AND Location IN ({0})", condition.Substring(0, condition.Length - 1));
}
using (SqlConnection con = new SqlConnection(VDIListConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query + condition))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void Location_Selected(object sender, EventArgs e)
{
this.BindGrid();
}
protected void Type_Selected(object sender, EventArgs e)
{
this.BindGrid();
}
你可以在連接創建之前放一個break,並且發佈名爲'condition'的變量的值嗎? – Kbalz