SelectedValue for a DropDownList in a DetailsView control
Setting the selected value for a dropdownlist in a detailsview control when in edit mode
Introduction
Setting the C# ASP.NET DetailsView control in Edit modus, trigger the DataBound event for the DetailsView control, and in this event handler populate a DropDownList and finally set the SelectedValue
of that DropDownList to the value of the underlying data. This might seem fairly easy, but there is a lot of confusion about it. Now here's the very basic guide to programmatically setting the default value for a DropDownList in a DetailsView control.
Prerequisites
You need a detailsview control into the HTML-part (name it DetailsView1 in the .aspx file) and use templated fields, and somehow bind that control to data. You also need to set the OnDataBound
event in the detailsvei control. Set it to point to a method in your code behind file (aspx.cs). Example: OnDataBound="DetailsView_Databound"
. And finally you need a DropDownList inside the EditItemTemplate
of your choice.
Procedure
protected void DetailsView_Databound(Object sender, EventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
{
DropDownList dropper = (DropDownList)DetailsView1.FindControl(
"inserthereThe_id_ofYourDropDownControl");
if (dropper != null)
{
dropper.DataSource=FunctionThatReturnsData(); // This could be a list for instance
dropper.DataBind();
if (dropper.Items.Contains(dropper.Items.FindByValue(DataBinder.Eval(
DetailsView1.DataItem, "UnderlyingDataFieldName").ToString())))
{
dropper.SelectedIndex = dropper.Items.IndexOf(
dropper.Items.FindByValue(DataBinder.Eval(DetailsView1.DataItem,
"UnderlyingDataFieldName").ToString()));
}
}
}
}