Click here to Skip to main content
15,886,199 members
Articles / Web Development / ASP.NET

Workaround when SQLDataSource doesn't Maintain SelectCommand on Postback

Rate me:
Please Sign up or sign in to vote.
4.14/5 (3 votes)
17 Sep 2007CPOL1 min read 28.4K   12  
This small piece of article explains how to solve the issue when the SQLDataSource doesn't maintain the latest SelectCommand between postbacks.

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:

VB
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.

ASP.NET
<%@ 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).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --