Wednesday, May 18, 2011

Programmatically adding Query Parameter to ASP.NET DomainDataSource

I love the new ASP.NET DomainDataSource because it allows me to talk to my Domain Service.

You could do this declaratively like the following:


<asp:DomainDataSource ID="dsDetails" runat="server">
        <asp:ControlParameter ControlID="GridView1" PropertyName="SelectedValue" Name="id" Type="Int32" />

In this example, this a DomainDataSource that I have connect to a FormView. I want the FormView to update when a GridView called GridView1.SelectedValue changes. I am setting the QueryName and the DomainServiceTypeName in my Page_Init so you don’t see it in the declaration above, but you could put it there as well.

In this scenario, the Query in my Domain Service is expecting a parameter called id. This must the Name property of the ControlParameter control.

Programmatically (Good Option)

We can do the same thing with the parameters, but this time do it programmatically. The declaration would now look like this:

<asp:DomainDataSource ID="dsDetails" runat="server">

Notice there is not QueryParameters declared, so we need to do this in code. The best place is in the Page_Init() method since it is very early in the page lifecycle.

Add the following line to the Page_Init() method:

dsDetails.QueryParameters.Add(new ControlParameter("id", TypeCode.Int32, "GridView1", "SelectedValue"));

This will do exactly the same as doing it declaratively, but now you nave more control of all the values passed since you are in code. One thing to point out is that when the GridView1.SelectedValue changes, the dsDetails datasource executes the query again automatically. That is why I like this method.

Programmatically (Okay Option)

The above is identical and great and my first choice. This approach here works best if you are getting your value from something that doesn’t change like the QueryString. If you need to set the current user, or some other value (like a querystring value) and don’t care that the dsDetails DomainDataSource will NOT be updated automatically and you will instead need to tell it to databind using something like SelectedItemChanged in the GridView1, you can use the Querying event on the DomainDataSource. In this case you would do the following.

<asp:DomainDataSource ID="dsEditor" runat="server"  
    onquerying="dsEditor_Querying" >

protected void dsDetails_Querying(object sender, Microsoft.Web.UI.WebControls.DomainDataSourceQueryingEventArgs e)
    e.QueryParameters.Add("id", GridView1.SelectedValue);

No comments: