Wednesday, March 21, 2007

ASP.NET SqlDataSource Parameters Don't play with HiddenField controls

A little piece of information that might be helpful to someone...
If you have a SqlDataSource that has parameters and you are binding them to a control, you may have problems if you try binding them to HiddenField controls.

I had a simple gridview that was looking up records based on an ID. I had everything working fine with the sqldatasource bound to a session variable called session("myid"). But, I decided I wanted to cache the value on the page to eliminate timeout issues. So I added a hiddenfield to the page. In the page load event I set this hiddenfield with the ID value, just like I did with the session, but the grid would not pull the records anymore. I tried calling DataBind on the grid and even on the SqlDataSource and it doesn't pull the records.

When I changed the variable back to a session variable it worked just fine. I didn't have to call Databind. The SqlDataSource is smart enough to detect a change in the parameter and will refresh.

I also tried using a label control. This one worked fine too. In my instance, I just wrote at the top of the page "Welcome [label with my userid]" and I was on to the next task.

Happy Coding!

1 comment:

  1. Yet another fix I've found for this is to set the style of the control to display:none and that way the control isn't hidden in reality. I actually use this trick on all my grid collumns I don't want to display because sometimes it goofs up the queries when you start leaving stuff out.