Skip to main content

QueryBuilder

Wisej.NET 4.2.0+

A QueryBuilder with two rules in the root group, a nested ANY group, and the expression preview.

A QueryBuilder lets users put together a filter the way they would say it: all of these conditions, and any of those. Each condition is a rule (a field, a comparison and a value), rules sit in groups joined by AND or OR, and groups nest inside groups. Below the editor an optional preview spells the result out as an expression.

Use it for the "advanced search" of a screen, for saved views and report criteria, for alert and routing rules: anywhere a fixed row of filter boxes cannot express what users need. The control does not query anything itself. It produces a validated tree of QueryGroup and QueryRule objects that you translate into a parameterized query, a LINQ predicate or a filter on a DataGridView.

info

For a complete list of properties, methods, and events, see the API documentation.

Features​

Fields​

The fields a rule can use are FilterField objects in the Fields collection. A field has a Name, the stable key that rules and saved queries refer to, a Text the user sees, a Type, and for a choice field its Choices. FilterFieldType sets the editor and the literal the field accepts:

TypeEditor and literal
TextFree text. The only type that allows contains and starts with.
NumberAn invariant number, such as 1250.5.
DateA date written yyyy-MM-dd.
Booleantrue or false.
ChoiceOne of the field's Choices, which are both the keys and the captions.

A field is immutable: replace its entry in the collection to change it. Field names are unique, and a field that a rule still uses cannot be removed. Configure the fields before you add rules or load a saved query.

Rules and Groups​

The query is a tree that starts at Root, a QueryGroup. A group has a Logic (QueryLogic.And for ALL, QueryLogic.Or for ANY), a Rules collection of QueryRule and a Groups collection of child groups. A rule has a Field, an Operator and a Value, always a string in the invariant format of the field's type.

QueryOperator offers Equal, NotEqual, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, Contains, StartsWith, IsNull and IsNotNull. The ordered comparisons need a number or date field, and Contains and StartsWith a text field. MaxDepth limits how deep groups can nest, from 0 to 16; the default is 3.

Validated on the Server​

Every change, whether the user makes it in the browser or your code makes it to an attached group or rule, is validated against the fields on the server. An invalid change is rolled back and leaves the previous tree intact. A rule that names an unknown field, an operator the field's type does not allow, or a value that does not parse is never accepted. A group or rule can belong to one tree only and appear in it once. To change a rule's field, operator and value together, replace the rule with a new one.

Expression Preview and JSON​

With ShowPreview set to true, the default, the control shows the query as an expression under the editor, such as ([Status] = 'Shipped' AND [OrderTotal] >= 500). ToExpression() returns the same text. It is meant for people to read; it is not SQL and must not be executed.

ToJson() serializes the tree, using field names and invariant values, so a query can be stored and loaded again with FromJson(). FromJson() validates the whole tree against the current fields and replaces the query in one step; when the JSON is malformed or names an unknown field, operator or value it throws, and the existing query is kept.

Events​

QueryChanged is raised after every accepted change to the query or to the fields. RuleAdded and RuleRemoved are raised for each rule entering or leaving the query, including all the rules of a group added or removed at once; their QueryRuleEventArgs carry the Rule.

How To​

Define Fields and a Starting Query​

this.queryBuilder1.Fields.Add(new FilterField("Status", "Status", FilterFieldType.Choice,
new[] { "Open", "Shipped", "Delivered", "Returned" }));
this.queryBuilder1.Fields.Add(new FilterField("OrderTotal", "Order total", FilterFieldType.Number));
this.queryBuilder1.Fields.Add(new FilterField("OrderDate", "Order date", FilterFieldType.Date));
this.queryBuilder1.Fields.Add(new FilterField("Region", "Region", FilterFieldType.Choice,
new[] { "EU", "AM", "APAC" }));
this.queryBuilder1.Fields.Add(new FilterField("Customer", "Customer", FilterFieldType.Text));

this.queryBuilder1.Root.Rules.Add(new QueryRule("Status", QueryOperator.Equal, "Shipped"));
this.queryBuilder1.Root.Rules.Add(new QueryRule("OrderTotal", QueryOperator.GreaterThanOrEqual, "500"));

var regions = new QueryGroup { Logic = QueryLogic.Or };
regions.Rules.Add(new QueryRule("Region", QueryOperator.Equal, "EU"));
regions.Rules.Add(new QueryRule("Region", QueryOperator.Equal, "APAC"));
this.queryBuilder1.Root.Groups.Add(regions);

Translate the Query into SQL Parameters​

Walk the tree and emit a parameter for every value. The column comes from a fixed map of field names, never from the rule, so nothing the user typed reaches the SQL text.

string Where(QueryGroup group, SqlCommand cmd)
{
var parts = group.Rules.Select(r =>
{
var column = Columns[r.Field]; // e.g. { "OrderTotal", "o.Total" }
if (r.Operator == QueryOperator.IsNull) return column + " IS NULL";
if (r.Operator == QueryOperator.IsNotNull) return column + " IS NOT NULL";
var p = cmd.Parameters.AddWithValue("@p" + cmd.Parameters.Count, r.Value).ParameterName;
return r.Operator switch
{
QueryOperator.Equal => $"{column} = {p}", QueryOperator.NotEqual => $"{column} <> {p}",
QueryOperator.GreaterThan => $"{column} > {p}", QueryOperator.GreaterThanOrEqual => $"{column} >= {p}",
QueryOperator.LessThan => $"{column} < {p}", QueryOperator.LessThanOrEqual => $"{column} <= {p}",
QueryOperator.Contains => $"{column} LIKE '%' + {p} + '%'",
_ => $"{column} LIKE {p} + '%'"
};
}).Concat(group.Groups.Select(g => Where(g, cmd)).Where(s => s.Length > 0)).ToList();
return parts.Count == 0 ? "" : "(" + string.Join(group.Logic == QueryLogic.And ? " AND " : " OR ", parts) + ")";
}

Values are strings in the invariant format; convert numbers and dates to their column types before passing them on when your database needs it.

Refresh Results as the Query Changes​

private void queryBuilder1_QueryChanged(object sender, EventArgs e)
{
using (var cmd = new SqlCommand())
{
var where = Where(this.queryBuilder1.Root, cmd);
cmd.CommandText = "SELECT * FROM Orders o" + (where.Length > 0 ? " WHERE " + where : "");
this.dataGridView1.DataSource = this.db.Fill(cmd);
}
this.expressionLabel.Text = this.queryBuilder1.ToExpression();
}

Save and Restore a View​

// Save the query with the user's view.
view.Criteria = this.queryBuilder1.ToJson();

// Restore it later; the fields must be configured first.
try
{
this.queryBuilder1.FromJson(view.Criteria);
}
catch (Exception)
{
// Unknown fields, invalid values or malformed JSON: the current query is kept.
AlertBox.Show("This saved view no longer matches the available fields.", MessageBoxIcon.Warning);
}

Advanced​

JavaScript Widget​

ItemDescription
Class name"wisej.web.QueryBuilder"
Theme appearance"querybuilder", and "querybuilder-group", "querybuilder-logic", "querybuilder-hint", "querybuilder-select", "querybuilder-input", "querybuilder-action" and "querybuilder-preview" for its parts. See Themes.