Populating Drop Down List Selected Item while DetailsView in Edit mode

Populating Drop down list when DetailsView is in Edit mode is explained in another article Binding Drop down list when DetailsView is in edit mode.

It is common requirement when you are redirecting from Master page to details page where DetailsView control is used to display single record on second page or GridView and DetailsView are used on a single page. When the user selects Edit button to edit data within DetailsView control, it is common requirement to populate the previous value as selected item in drop down list. So that end user can either change previous value in drop down list or stick to current value being populated.

This article explains how to achieve this requirement from code behind.

ASPX

Below is the ASPX code to display country. When DetailsView in in Read-only mode Label control is used to display the relevant record country from “country”  database column, when DetailsView is in edit mode controls within EditItemTemplate are used to populate data.

Here Drop Down List control is used to populate list of countries when DetailsView in edit mode.

<asp:TemplateField HeaderText="Country">
 <ItemTemplate>
   <asp:Label ID="lblCountry" runat="server" 
   Text='<%# bind("country")%>' />    
 </ItemTemplate>

 <EditItemTemplate>
    <asp:DropDownList ID="ddlCountry" runat="server"  
       AppendDataBoundItems="True" >
       <asp:ListItem Value="" Text="" />
    </asp:DropDownList>   
 </EditItemTemplate>
</asp:TemplateField>

Code behind

Details view Data Bound event is used to populate drop down list selected item as shown below.

//Populate previous value as selected item
protected void dvUserRecord_DataBound(object sender, EventArgs e)
{
   //check for DetailsView mode is Edit
   if (dvUserRecord.CurrentMode == DetailsViewMode.Edit)
    { 
            
      //Get reference to Country drop down list
    DropDownList ddlCountry = 
    dvUserRecord.FindControl("ddlCountry") as DropDownList;
    
     if (ddlCountry != null)
      {
      //Data binding Drop down list source code here
      //This is discussed in another article 
         
      //Then populate SelectedItem
        
      //Get current record country and set as 
      //selected item in Country drop down list
      DataRowView row = dvUserRecord.DataItem as 
      DataRowView;
      if (row != null)
      {  
         //Get current record country
          ListItem liCountry = ddlCountry.Items.
          FindByText(row["country"].ToString());
      
      //Set as selected List item in Drop down list
        if (liCountry != null)
         {
            ddlCountry.Items.FindByText(row["country"].
            ToString()).Selected = true;
        
           }
         }
      }
     
}

That’s it! you are ready to fly…

1 Comment

Comments have been disabled for this content.