Search code examples
c#.netregexbindingsource

.NET BindingSource.Filter with regular expressions


i am using a BindingSource.Filter to list only certain elements of the datasource. especially i use it like this a lot:

m_bindingSourceTAnimation.Filter = "Name LIKE '" + FilterText + "'";

now my question is, if it is somehow possible to use regular expressions with these filters.

i would especially need multiple wildcard (*) characters like

*hello*world*

thanks!


Solution

  • You can query the DataTable with LINQ pretty easily and then you can use a actual Regex within the query to filter it anyway you like.

    Something like this...

    var source = myDataTable.AsEnumerable();
    
    var results = from matchingItem in source
                  where Regex.IsMatch(matchingItem.Field<string>("Name"), "<put Regex here>")
                  select matchingItem;
    
    //If you need them as a list when you are done (to bind to or something)
    var list = results.ToList();
    

    This will get you the rows that match based on an actual Regex, I don't know what you need to do with the information, but this would allow you to get the rows based on a Regex.

    ****Update** - Trying to clarify based on comment

    I don't know what you are using this for so I don't have a great context, but from what I can guess you are using a DataTable to data bind to a Grid or something like that. If this is the case, I think that you should be able to assign "list" from the snippet I put in here as the DataSource (assuming you are using a BindingSource) and I think that it will work. I don't use DataTables, I usually stick to objects for working with my data so I am not exactly sure how it will handle the list of rows, but I would think that it would work (or be close enough that a little google searching would do it).