views:

28

answers:

1

I fill a DataSet and allow the user to enter a search string. Instead of hitting the database again, I set the RowFilter to display the selected data. When the user enters a square bracket ( "[" ) I get an error "Error in Like Operator". I know there is a list of characters that need prefixed with "\" when they are used in a field name, but how do I prevent RowFilter from interpreting "[" as the beginning of a column name?

Note: I am using a dataset from SQL Server.

+1  A: 

So, you are trying to filter using the LIKE clause, where you want the "[" or "]" characters to be interpreted as text to be searched ?

From Visual Studio help on the DataColumn.Expression Property :

"If a bracket is in the clause, the bracket characters should be escaped in brackets (for example [[] or []])."

So, you could use code like this :

        DataTable dt = new DataTable("t1");
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Description", typeof(string));

        dt.Rows.Add(new object[] { 1, "pie"});
        dt.Rows.Add(new object[] { 2, "cake [mud]" });

        string part = "[mud]";
        part = part.Replace("[", "\x01");
        part = part.Replace("]", "[]]");
        part = part.Replace("\x01", "[[]");

        string filter = "Description LIKE '*" + part + "*'";

        DataView dv = new DataView(dt, filter, null, DataViewRowState.CurrentRows);

        MessageBox.Show("Num Rows selected : " + dv.Count.ToString());

Note that a HACK is used. The character \x01 (which I'm assuming won't be in the "part" variable initially), is used to temporarily replace left brackets. After the right brackets are escaped, the temporary "\x01" characters are replaced with the required escape sequence for the left bracket.

Moe Sisko
This example works great. When I try to use the same techniques in my program (SQL Database), I get no results. It seems like the SQL ADO driver is the source of the problem?Also, if I try it in Query Analyzer, a trailing bracket ("]") returns expected results, but using a leading bracket("[") yields no results. Using both returns rows containing any of the letters enclosed in the brackets.
Jeff Corder
@Jeff - that sounds strange. Once the data is in the DataSet, it shouldn't matter that the source of the data was SQL server. Also, the LIKE clause of DataColumn.Expression is a different animal to SQL Server's T-SQL LIKE clause.
Moe Sisko

related questions