FOLLOW US
4dots Software CODE BLOG

How to escape LIKE value in .NET

We can select specific rows of a DataTable in .NET based on various criteria. We can filter the results also using the LIKE operator.
For example, we could do something like that :
	

dataGridView1.DataSource=dataTable1.Select("[ProductName] LIKE 'York'");

The problem is when the values we want to find contain the [,],%,* or ' characters.
We have to filter these characters.
To do this use the following :
	

	public static string EscapeLikeValue(string value)
	{
		StringBuilder sb = new StringBuilder(value.Length);
		for (int i = 0; i < value.Length; i++)
		{
			char c = value[i];
			switch (c)
			{
				case ']':
				case '[':
				case '%':
				case '*':
					sb.Append("[").Append(c).Append("]");
					break;
				case '\'':
					sb.Append("''");
					break;
				default:
					sb.Append(c);
					break;
			}
		}
		return sb.ToString();
	}
        

Now we can do something like the following :
	

 string product_name_string="York %301%";
 
 dataGridView1.DataSource=dataTable1.Select("[ProductName] LIKE '" + EscapeLikeValue(prodct_name_string) + "'");
 

 

Please Donate!

Please Share!