Friday, July 1, 2011

Smart Search Filter

Introduction

In Iron Speed Designer, it is very easy to add a search filter above a table control. It is also very easy to config the filter to work in Equals, StartsWith, EndsWith or Contains mode. At design time, I always set search filters in Contains mode to get the most search power. At run-time, however, Contains mode sometimes returns too many hits. These are the times I wish I could double-quote the search text, and the filter would automatically switch to Equals mode.

This turns out to be a pretty straightforward customization.

Code customization

Use the following convention to define a search filter's operator:
TextOperator
"search term"Equals
"search termStartsWith
search term"EndsWith
search termContains

Override the table control's CreateWhereClause() method. Find the code block that defines the search behavior. Insert the following code right before the WhereClause is declared.

var searchOp = BaseFilter.ComparisonOperator.Contains;
if (formatedSearchText.StartsWith("\"") && formatedSearchText.EndsWith("\"")) {
  searchOp = BaseFilter.ComparisonOperator.EqualsTo;
  formatedSearchText = formatedSearchText.Substring(1, formatedSearchText.Length - 2);
} else if (formatedSearchText.StartsWith("\"")) {
  searchOp = BaseFilter.ComparisonOperator.Starts_With;
  formatedSearchText = formatedSearchText.Substring(1);
} else if (formatedSearchText.EndsWith("\"")) {
  searchOp = BaseFilter.ComparisonOperator.Ends_With;
  formatedSearchText = formatedSearchText.Substring(0, formatedSearchText.Length - 1);
}

Then replace the search operator in the WhereClause:
WhereClause search = new WhereClause();
search.iOR(CustomersTable.CustomerID, searchOp, formatedSearchText, true, false);
search.iOR(CustomersTable.CompanyName, searchOp, formatedSearchText, true, false);
search.iOR(CustomersTable.EmailAddress, searchOp, formatedSearchText, true, false);
search.iOR(CustomersTable.City, searchOp, formatedSearchText, true, false);
search.iOR(CustomersTable.Region, searchOp, formatedSearchText, true, false);
search.iOR(CustomersTable.PostalCode, searchOp, formatedSearchText, true, false);


Conclusion

Now you have a smart search filter.

No comments: