How to apply filter to DataView with Multiple "AND" conditions

SHEKHAR SHETE picture SHEKHAR SHETE · Oct 16, 2013 · Viewed 37.2k times · Source

I have a DataTable containing the some rows. Which is copied to DataView. Now I have IDs in form of List<string>. which contains the selected items from GridView. Now I want to filter this DataView using AND as filter.

When I apply just one it works, but applying multiple AND doesn't work.

In .cs :

List<string> selectedAddress = new List<string>();
protected DataView GetSelectedItems()
{
    DataView dv = new DataView(dtresult);
    int count = selectedAddress.Count();
    if (count > 0)
    {
        string query = "ID=";

        for (int j = 0; j < selectedAddress.Count; j++)
        {
            string val = selectedAddress[j].ToString();
            if (j == 0)
            {
                query += val + " and ";
            }
            else
            {
                query += "ID=" + val + "";
            }
        }
        dv.RowFilter = query;
    }
    return dv;
}

Any idea?

Answer

Somnath picture Somnath · Feb 4, 2014

Try this:

List<string> selectedAddress = new List<string>();
protected DataView GetSelectedItems()
{
    DataView dvResult = new DataView(dtresult);
    string query = "";
    int count = selectedAddress.Count();

    for (int j = 0; j < selectedAddress.Count; j++)
    {
        string val = selectedAddress[j].ToString() + ",";
        query += val;
    }

    query = query.Remove(query.Length - 1);
    dvResult.RowFilter = "ID IN(" + query + ")";
    return dvResult;
}