如何在asp.net中显示基于多选择下拉项的gridview记录
本文关键字:选择 记录 gridview 于多 asp net 显示 | 更新日期: 2023-09-27 18:06:23
在我的应用程序中,我有多个选择下拉列表和基于选择,我需要在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 + ")";