Search code examples
c#datagridviewdatatablerowfilter

How to use a RowFilter on a DataTable to find rows where a column is both not null and greater than/less than a value?


I'm trying to filter a DataTable of x, y, z coordinate values within a certain range for each of them. For example, I want to see the rows with an x value greater than 200. My issue is that the DataTable is read in from a DataGridView and all of the fields are interpreted as strings. Additionally, several rows are missing at least one x, y, or z value, so I want to exclude those.

As a test on just the x values, I've tried

(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = "[X Value] 
IS NOT NULL AND CONVERT([X Value], 'System.Decimal') > 200.0";

and this results in the error message "Input string was not in a correct format." I assume this is happening because it's trying to convert a null value into a decimal. I get the same issue when the row filter does not include the [X Value] IS NOT NULL half.

Is it possible to do this all in a single RowFilter?


Solution

  • No, the AND ensures that if the first condition is not met, the second condition is not evaluated. So the error is not caused by a null value, but with great probability by an empty string.

    Just change your test to

    "[x value] IS NOT NULL AND [x value] <> '' AND CONVERT([x value], 'System.Decimal') > 200.0";