Text Filtering with Dynamic Data

Dynamic Data provides a good architecture for adding custom filters to your application. To read more about understanding filtering read the following post

In this post I am going to take you through a walkthrough of how you can write your own search filter. This sample builds on writing LinqExpressions. If you want more information about Linq Expressions you can learn more from here

1. Add a FilterUserControl  called “Search” to the DynamicData/Filters template(You can use the one attached to this post)

The Search user control has a textbox which takes in the search input and a button control

2. In the Code behind of search.ascx override the GetQueryable() method to return the filtered query as follows

 public override IQueryable GetQueryable(IQueryable source)
    {

        if (Column.TypeCode != TypeCode.String)
            return source;


        string searchString = TextBox1.Text;
        if (TextBox1.Text == "")
            searchString = String.Empty;
        Type type = typeof(String);



        string searchProperty = Column.DisplayName;
        ConstantExpression searchFilter = Expression.Constant(searchString);


        ParameterExpression parameter = Expression.Parameter(source.ElementType);
        MemberExpression property = Expression.Property(parameter, this.Column.Name);
        if (Nullable.GetUnderlyingType(property.Type) != null)
        {
            property = Expression.Property(property, "Value");

        }
        MethodInfo method = typeof(String).GetMethod("Contains", new[] { typeof(String) });

        var containsMethodExp = Expression.Call(property, method, searchFilter);
        var containsLambda = Expression.Lambda(containsMethodExp, parameter);


        var resultExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { source.ElementType }, source.Expression, Expression.Quote(containsLambda));

        return source.Provider.CreateQuery(resultExpression);

    }
 3. Add an event to Raise the Filter changes event. In this sample it is the ButtonClicked() event as shown
  
  protected void Button1_Click(object sender, EventArgs e)
    {
        OnFilterChanged();
    }

4. Add FilterUIHint(“Search”) to a string column eg. ProductName column in Products table of Northwind database.

You can download this sample that has the Search.ascx user control from here