[英]How can i show the selected items as comma separated in the Multi select dropdown text field in asp.net
[英]How can i display gridview records based on multi selected dropdown items in asp.net
在我的應用程序中,我有多個選擇的下拉列表,並且基於選擇,我需要顯示在gridview中。 如果我從多重選擇下拉列表中選擇兩個項目,則需要在gridview上顯示兩個選定的記錄。下面的代碼是我選擇了兩個項目,我只會得到第一個選擇記錄。
我試過代碼:
protected void ddlcol2_SelectedIndexChanged(object sender, EventArgs e)
{
string qry = "select * from Collections where col1='" + ddlcol1.SelectedValue.ToString() + "' and col2='" + ddlcol2.SelectedValue.ToString() + "'";
SqlCommand cmd = new SqlCommand(qry,con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
如果我從ddlcol2中選擇兩項,則ddlcol2是多選下拉菜單,我想在gridview上顯示兩項記錄。
誰能告訴我該怎么做。
謝謝
假設ddcol1
是單選
更改查詢字符串以接受多個值
string qry = "select * from Collections where col1='" +
ddlcol1.SelectedValue.ToString() +
"' and col2 in ('" +
string.Join("','", ddlcol2.Items.Cast<ListItem>
.Where(i => i.Selected)
.Select(i => i.Value)
.ToArray()) + "')";
編輯 ( 不使用LINQ )
var sCol2 = string.Empty;
foreach(var item in ddlcol2.Items)
{
if (item.Selected)
sCol2 += "'" + item.Value + "',"
}
// remove the last ,
if (sCol2.Length > 0)
sCol2 = sCol2.Substring(0, sCol2.Length - 1);
string qry = "select * from Collections where col1 = '" +
ddlcol1.SelectedValue.ToString() +
"' and col2 in (" +
sCol2 + ")";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.