Wednesday, February 22, 2012

Passing on ViewState Items onto ObjectDataSource

Because the datasource instance does not run in your page instance, you will not be able to fetch your ViewState items. The only way to do this is to pass it on to the parameters. Suppose you've got a gridview, using an object data source instance called 'odsBand' and you would like to retrieve a DataSet from your db filtered by band name. In this case you need to define a electParameter which will hold the band name retrieved from your ViewState. See markup below

<asp:ObjectDataSource ID="odsBands" runat="server" 
        <asp:Parameter Name="BandName" Type="String" />

Here I set up the BandName property which will chuck the request band name string into the ViewState:

private string BandName
        return ViewState["BandName"] == null ? "" : ((string)ViewState["BandName"]);
        ViewState["BandName"] = value;

In the Page_Load method, I'm putting the QueryString into the Viewstate, using the BandName property:

protected void Page_Load(object sender, EventArgs e)
    odsBands.TypeName = this.GetType().AssemblyQualifiedName;
    if (!Page.IsPostBack)
        BandName = Request.QueryString["bandName"];
        // This is my SPGridView instance which will display the data
        grdBand.DataSourceID = "odsBands";

Ok cool. From here I use the property to set the input parameter 'BandName' like this:

protected void odsBands_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    e.InputParameters["BandName"] = BandName;

Finally, I define the SelectMethod 'SelectBands' with one string argument which is the input parameter. In this particular case I'm using a DataSet from which I then create a DataView to filter on the parameter value:

public DataView SelectBands(string bandName)
    // The method below fetches the data from a db, replace this with your own source
    DataSet dsBands = BandsResourceManagement.Instance.GetBands();
    // BandName is also the field name in the table and I'm sorting the records by the field BandId
    DataView dvBand = new DataView(dsBands.Tables[0],"BandName = '" + bandName + "', "BandId", DataViewRowState.CurrentRows);