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 !









