HelloWorld
HelloWorld

Reputation: 43

How to filter DataView based on multiple inputs

I know how to filter data based on the user's input from a single textbox:

FilterDataView.RowFilter = txtFilter.Text;

But how would you go about filtering data based on multiple user input from multiple fields. Basically filter would act as a "search" functionality.

Upvotes: 1

Views: 14070

Answers (3)

HABJAN
HABJAN

Reputation: 9328

You can use something like light t-sql when defining RowFilter.

One idea is:

FilterDataView.RowFilter = "name like '%habjan%' and city like '%new york%'"

Here you can find a good article about RowFilter syntax: DataView RowFilter Syntax

For what you need you will have to build row filter based on entered fields.

    StringBuilder sb = new StringBuilder();

    if (tb1.Text.Length > 0)
    {
       sb.Append("name like '%" + tb1.Text + "%'");
    }

    if (tb2.Text.Length > 0)
    {
       if(sb.Length > 0)
       {
           sb.Append(" and ");
       }

       sb.Append("city like '%" + tb2.Text + "%'");
    }
    //.... and so on...

    FilterDataView.RowFilter = sb.ToString();

Upvotes: 5

Michael27
Michael27

Reputation: 159

Search the MSDN(LINQ to DataSet) http://msdn.microsoft.com/en-us/library/bb669073.aspx

Upvotes: 1

nycdan
nycdan

Reputation: 2839

Okay, Linq to SQL is going to be your friend.

You need to learn the syntax, and there are a few different forms, but you can recreate your query in this way:

var x = from T in db.Table
        where [usual where stuff goes here];

Then, you can test each textbox and do the following:

if (TextBox1.Text != null) x.Where(w => w.field1 == val1);

The nice thing is you can layer those Where clauses one at a time. Then just bind your object to the var.

[objectname].Datasource = x; 
[objectname].Databind();

That should solve your problem.

Upvotes: 0

Related Questions