views:

312

answers:

2

Is it possible to write extension methods for expressions behind RDLC fields?

For example, let's say that I have a DateTime field in my datasource that may either have a valid value or may be null. I drag and drop a TextBox onto my RDLC and format its value using the ToShortDateString() method. This works fine for populated DateTime value, but this will also obviously throw an exception at runtime if I try to do a .ToShortDateString() on a NULL field.

I was wondering if I could write an extension method that I could use in my RDLC expressions so that when I'm dealing with ?DateTime values, I could call a method like .ConvertFromNullToEmptyString().

Of course there are other ways to work around this issue, but I was wondering if extension methods for use in RDLC expressions would be a possible approach to my business problem.

Thanks folks!

+2  A: 

Yes, this is possible. You can either embed code directly in the report or include a custom assembly.

Corina
@Corina: Those aren't examples of using extension methods - which is what the question is asking...
DanP
@DanP: while this doesn't add extension methods, calling the code is the done in the same way as the normal expressions.
MasterMax1313
A: 

While I agree with Corina on the solution to the question, I believe a better solution can be reached without going the route she suggests, using built in expressions. In any case where you have a DateTime coming from SQL, you're correct, it can be null, however, you can easily test for this using an IIF statement (remember that the expressions are basically in VB) to check for null / nothing / empty and as long as it is something, run the desired operation, otherwise return blank. Just be careful, as the resulting type of the IIF will probably be string.

MasterMax1313
@MasterMax1313: While I can't spreak for the OP or AMissico; I'm personally interested in extension methods specifically. It is already very well known how to use arbitrary custom code in a report - so answers along those lines are somewhat pointless...
DanP
One of the challenges with what you're asking is that reflection is probably being used to execute the method, so if you call .ConvertFromNullToEmptyString() on the null object (null datetime), you'll get a null reference exception regardless, unless you rewrote the DateTime? object to have a static method called ConvertFromNullToEmptyString which would provide the functionality you're asking for. At the moment, I don't see how this particular piece of functionality benefits you more than a some custom code.
MasterMax1313