Search code examples
c#datatablerowfilter

Rowfiltering fails when filter text is having single quote


As my tiltle clearly mentions I am trying to filter the datatable with a filter text having single quote in it .

My statement is as follows

dgURComments.ItemsSource).ToTable().Select("URComments = '" + txtComments.Text.Trim() + "'");

How can I overcome from this ?


Solution

  • Instead of fiddling around with DataTable.Select i would use Linq-To-DataSet:

    IEnumerable<DataRow> rows =  tbl.AsEnumerable()
           .Where(r => r.Field<String>("URComments") == txtComments.Text.Trim());
    

    If you need a DataTable from the filtered result, you can use CopyToDataTable

    DataTable tblFiltered = rows.CopyToDataTable();
    

    The minimum requirement is a reference to System.Core.dll and a using directive for System.Linq. By default, these are supplied if you create a new Visual C# 2008 project. LINQ to DataSet also requires a reference to System.Data.dll and System.Data.DataSetExtensions.dll and an using directive.