Friday, June 22, 2007

Selected Event not Firing for SqlDataSource: CancelSelectOnNullParameter

The problems I've had with declarative code are the subject of another post, but suffice it to say that I have not yet achieved "declarative enlightenment." Nevertheless, I dutifully trudge forward, using the SqlDataSource object instead of explicitly grabbing my data.

The main idea behind declarative programming is to make programmer intent more easily expressible and creating a SqlDataSource and telling a control the ID of that data source is right in-line with that idea. Unfortunately, things break down when the code running behind the declarative markup makes assumptions about your intent that are non-intuitive.

Enter the Boolean CancelSelectOnNullParameter of the SqlDataSource. This very well-named property defaults to TRUE. That's right, if you have multiple parameters on your SelectCommand and one of them is null, the SqlDataSource will not execute the SelectCommand. The page will blithely continue executing and the control(s) that are bound to the SqlDataSource will not get populated.

Interestingly, the Selecting event of the SqlDataSource will fire but the Selected event will not. This makes perfect sense: what doesn't make sense is the default. Cancelling the SelectCommand is an optimization--APIs should NEVER make an assumption around an optimization.