views:

289

answers:

2

Hi,

In my application I am using a dataview for having the filters to be applied where the filter options are passed dynamically.if there are 2 filter parameters then the dataview should be filtered for parameter1 and then by parameter two. I am using a method which is called in a for loop where I am setting the count to the total no.of parameters selected using a listbox but the filtering is done only for the last parameter. Here is my code:

string str = "";
for (int i = 0; i < listbox.Items.Count; i++)
{
    if (listbox.Items[i].Selected)
    {
     if (str != string.Empty)
     {
      str = str + "," + listbox.Items[i].Text;

     }
     else
     {
      str = str + listbox.Items[i].Text;
     }
    }
}

string[] items = str.Split(',');
for (int i = 0; i < items.Length; i++)
{
    ApplyFilter(items[i],dv);
}

private DataView ApplyFilter(string str,DataView newdv)
{
    newdv.RowFilter = "[" + str + "]=" + ddl.SelectedItem.ToString();

    return newdv;
}

Please provide a suitable solution .

Thanks in advance...

+1  A: 

You should apply your filter altogether, not one by one :

newdv.RowFilter = "Column1 = " + value1 + " AND Column2 = " + value2;

So you can change your code as :

string[] items = str.Split(',');
string filter = string.Empty;
for (int i = 0; i < items.Length; i++)
{
    filter += items[i] + " = " + dropdown.SelectedValue;
    if (i != items.Length - 1)
    {
         filter += " AND ";
    }
}
newdv.RowFilter = filter;
Canavar
but iam not sure of how many filter parameters will be passed.how to add the columns in the same rowfilter
Thanks for the response. it is working fine.
A: 

I think you should build a complete filter string and then set this filter to your DataView. For example:


StringBuilder sb = new StringBuilder()
for (int i = 0; i < listbox.Items.Count; i++) {
  if (!listbox.Items[i].Selected) {
    continue;
  }

  if (sb.Length > 0) {
    sb.Append(" and ");
  }
  sb.AppendFormat("[{0}] = {1}", listbox.Items[i].Text, ddl.SelectedItem);
}

dv.RowFilter = sb.ToString();
Tadas