Click here to Skip to main content
Click here to Skip to main content

SelectedValue for a DropDownList in a DetailsView control

, 25 Aug 2013
Rate this:
Please Sign up or sign in to vote.
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()));
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

netfed
Student
Norway Norway
Programming in C# for web, desktop and server. Systems integration as a speciality.

Comments and Discussions

 
Generalthanks Pinmembermathewtinu12-Jul-14 3:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 25 Aug 2013
Article Copyright 2013 by netfed
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid