WinForms, how to implement conditional format for DataGridViews
Being able to apply conditional formats to datagridviews is a must nowadays, users of our app probably make heavy use of this feature on Excel spreadsheets, and they want it to be present on any "grid alike" screen.
I’ll show you two ways to implement this feature the first one is using pre-built formats, or formats specified in C# at compile time (better performance) and the second one that allows users to add their own conditional formats with formulas written in an excel fashion. In the last case the performance is not good enough for prod., but I’ll be sanding rough edges and hopefully make it work in a near future.
To work on this feature, I'm going to use the same datagrid I used in the previous post, which you can download from here.
The whole functionality is already implemented, so I'll just show you how to use it.
The only thing you have to do is register the conditional format and the component will take care of the rest. To register a conditional format you have to specify a function (the conditional part) and the format to be applied if the function result is true. Something like this:
In order to apply all of the specified formats, we need to hook an event handler to the grid’s RowPrePaint event and evaluate each registered condition, if the result is true, the format is applied. (The component takes care of this; you don't have to do anything. It's just an implementation detail)
And this is the layout of our little sample.
In the next post, how to implement this behavior for user defined conditional formats.