Introduction
Definition of the Problem
Workarounds are generally referred to as temporary fixes, but I guess this one is kind of a permanent solution for the 2.0 version of ASP.NET due to the security policy of Microsoft. In the early beta versions of ASP.NET 2.0, SQLDataSource
was keeping the latest SelectCommand
between the postbacks. But now, it isn't. It is currently reverting to the one that was set when the original data source was created, probably during the first Page_Load
.
Why?
This is because SQLDataSource
doesn't store commands by default in the ViewState
since it is now possible to decrypt the ViewState
on the client side, and storing sensitive information this way would be somehow painful. But, there are cases when we may need to set the SelectCommand
across roundtrips for the same page.
Workaround
Solution
If functionality of the application is chosen over security, then we can manage to solve this issue by utilizing our own ViewState
.
A code sample can be like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not ViewState("Button1FiredCommand") Is Nothing Then
SQLDataSource1.SelectCommand = ViewState("Button1FiredCommand")
Else
SQLDataSource1.SelectCommand = "SELECT * FROM Table1"
End If
GridView1.DataSourceID = SQLDataSource1
End Sub
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
ViewState("Button1FiredCommand") = "SELECT * FROM Table1 WHERE Column1= 'Test'"
SQLDataSource1.SelectCommand = ViewState("Button1FiredCommand")
GridView1.DataSourceID = SQLDataSource1
End Sub
Additionally
We can also enable encryption of the ViewState
in order to protect its content at some level. The Page.ViewStateEncryptionMode
property can be used to do this. Its default value is Auto
and we need to force it to Always
.
<%@ Page Language="VB" ViewStateEncryptionMode="Always" %>
Don't forget that values set in the Page
directive override any values which were set in the configuration file(s).