The ASP.NET do and don’ts serie : episode 4 – If you retrieve server controls in your code-behind do it the safe way !

When we are developping with databound controls, a common action is to retreive controls (like dropdownlists) in an objectdatasource’s “Inserting” event.

Here is a specific example :

In the InsertItemTemplate of a ListView:


<asp:ObjectDataSource runat="server" ID="MyDataSource"
 // ... />

<asp:DropDownList runat="server"
       ID="MyDDL"
       DataSourceID="MyDataSource"
       DataTextField="TheText"
       DataValueField="TheValue"/>

Do:


protected void TheDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    if (MyListView.InsertItem == null)
       return;

     DropDownList myDDL= MyListView.InsertItem.FindControl("MyDDL") as DropDownList;
     if (myDDL== null)
         return;
     if (string.IsNullOrEmpty(myDDL.SelectedValue))
         return;

    e.InputParameters["TheWantedValue"] = myDDL.SelectedValue;
 }

Don’t:


protected void TheDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    e.InputParameters.Add("TheWantedValue", ((DropDownList)MyListView.InsertItem.FindControl("MyDDL")).SelectedValue);
}

This for an obvious reason : you can’t always be sure that a problem won’t pop up.

A random problem can occur anywhere, whether the dropdownlist population or something else

So, be safe and protect yourself !

Incoming search terms:

  • objectdatasourcemethodeventargs dropdownlist

About Sam Beauvois

Application Developer, .NET enthusiast since 2004, I'm interested in technology watch, usability, code quality, patterns & practices, UX, ...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>