Shiv Shiv - 2 months ago 6
ASP.NET (C#) Question

How can i display gridview records based on multi selected dropdown items in asp.net

In my application i have multi selected dropdownlist and based on selection i need to display in gridview. If i select two items from multi select dropdown based on that i need to display that two selected records on gridview.Below code is i selected two items i am getting first selection records only.

i tried code:

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 is the multi select dropdown if i select two items from ddlcol2 i want to display that two items records on gridview.

Can anyone please tell me to how to do this.

Thank you

Answer

Assume that ddcol1 is single select only

change the query string to accept multiple values

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()) + "')";

EDIT (without 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 + ")";
Comments