Setting parameters for DataSourceControls from code-beside (ASP.NET 2.0)

Information based on VS.Net 2005 Release Candidate 1

You have probably seen or heard how you can use the new ASP.NET 2.0 data-bound servercontrols to write data driven applications without writing a single line of code. To get a beter understanding of how this works, you can refer to this article.

 

This is all fine and dandy but what if you wanted to programatically set the parameters from your code beside? This can easily be accomplished as the following example shows.

 

Consider a data access layer called OrderDAL which had a method called GetOrders that returned a List<OrderDetails> like so.

 

[System.ComponentModel.DataObject]

public class OrderDAL {

 

[System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]

public List<OrderDetails> GetOrders(int employeeId, string shipCountry) {...}

}

 

public class OrderDetails {

    public int OrderId {...}

    public DateTime ShippedDate {...}

    public DateTime RequiredDate {...}

    public DateTime OrderDate {...}

    public string CustomerId {...}

}

 

We are going to call this method, GetOrders, and display its results in a GridView with the help of an ObjectDataSource control.

We first add an ObjectDataSource control to our aspx page.

 

Note that in my OrderDAL I have an attribute for the class and an attribute for the GetOrders method. By default, VS.Net will show all classes in your App_Code folder or bin folder. By clicking “Show only data components“ only those classes that have the DataObject attribute will be available in the dropdown menu. Likewise, the “choose method” dropdown in the “SELECT” tab will show all methods in the selected class that return a DataSet, DataReader or strongly typed collection. By setting a DataObjectMethod attribute to methods, only those methods will be available the dropdown menu if the “Show only data components” is checked.

 

We now configure the ObjectDataSource to execute the GetOrders method in the “SELECT” tab. In the  “Define parameters” section,  we choose “None” for the parameters whose values we wish to set in the codebeside (in this case both employeeId and shipCountry). A GridView is then added that has its DataSourceId set to this ObjectDataSource. The generated aspx code is shown below:

 

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetOrders"

    TypeName="OrderDAL" OnSelecting="ObjectDataSource1_Selecting">

    <SelectParameters>

        <asp:Parameter Name="employeeId" Type="Int32" />

        <asp:Parameter Name="shipCountry" Type="String" />

    </SelectParameters>

</asp:ObjectDataSource>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">

    <Columns>

        <asp:BoundField DataField="CustomerId" HeaderText="CustomerId" SortExpression="CustomerId" />

        <asp:BoundField DataField="OrderId" HeaderText="OrderId" SortExpression="OrderId" />

        <asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" />

        <asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate" SortExpression="ShippedDate" />

        <asp:BoundField DataField="RequiredDate" HeaderText="RequiredDate" SortExpression="RequiredDate" />

    </Columns>

</asp:GridView>

 

The ObjectDataSource, SqlDataSource and AccessDataSource controls (which all inherit from the System.Web.UI.DataSourceControl) raise, amongst others, the following events

 

public event ObjectDataSourceSelectingEventHandler Selecting;

public event SqlDataSourceStatusEventHandler Selected;

 

The Selecting event is raised before the ObjectDataSource controls retrieves the data from our DAL and the Selected event is raised after the data retrival operation is complete. You should subscribe to the Selecting event if you wish to perform data validation or to set/change the parameters for the method being executed.

 

You subscribe to the Selected event if you want to handle any exceptions raised as a result of the data retrival operation or perform operations based on the output of your method.

 

Since we want to set our parameters before the “select” operation, we will subscribe to the Selecting event. This can be done by selecting the ObjectDataSource, going to the events section under properties and double clicking on the Selecting event. The following code gets generated for you.

 

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {}

 

The ObjectDataSourceSelectingEventArgs has a property called InputParameters of type IDictionary which is a collection of the select parameters you defined.

 

We can now set our parameters like so:

 

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {

    e.InputParameters["employeeId"] = 5;

    e.InputParameters["shipCountry"] = "USA";

 

    //IDictionary parameters = e.InputParameters;

    //foreach (DictionaryEntry param in parameters) {

    //    Trace.Warn(String.Format("{0} - {1}", param.Key, param.Value));

    //}

}

 

This way the parameters get set in our code beside before the select method gets called.

 

The downside of using DataSourceControls - you loose strong typing

8 Comments

  • It's good one. Keep it up.

  • God I hate the DataSource control. It's a step backwords from 1.1 IMHO. The big point of .NET was OOP of pages and seperation of content from code. So what does this &quot;data-bound servercontrols to write data driven applications without writing a single line of code&quot; produce? Stored proc params, connection strings and SQL inside the asp. page, in the middle of the &quot;content&quot; where it doesn't belong.



    I'm all for the without-writing-code mantra, but they could have at least kept the old style DataAdapter/DataSet controls in the toolbox that at least put their code in the codebhind where it belongs.



  • Can you use this same technique to intercept a parameter and change it before it gets used by the SQL command. &nbsp;IE: Intercept the parameter (ClaimDate) and change it from format mm/dd/yy to yyyy-mm-dd.
    Thanks

  • I am trying to utilize this code in a Wizard. The problem is that I don't know the Select parameter value until after the first postback from the Step1 in the wizard. I tried to set the parameter value and manually call the Select method later in the wizard process. Does not seem to like it. Any ideas?

  • Christopher,
    Use the contact link on the top left to send me an email. After that, I will need you to send me a sample repro using the northwind database. This will make it easier for me to troubleshoot the issue.
    Raj

  • Hey Raj,

    Thanks for this article.
    It helped me as I have to set the value of select parameter from querystring with encrypted data. So I needed to first decrypt the data in code behind and then use that value for select parameter.

  • Hello Raj

    you explained ObjectDataSource beautifully.
    you solved my problem when i used overloaded method in Select Parameters

  • very useful article! Thanks !

Comments have been disabled for this content.