Patrick Coelho
Patrick Coelho

Reputation: 168

DropDownList returning a object, not only a ID value

I want a solution to implement a property (or method) to return the selected object.

Example:

DropDownListUser.DataSource = UserList;
User user = (User)DropDownListUser.SelectedObject;

Is this possible?

Upvotes: 1

Views: 8131

Answers (4)

Hailton
Hailton

Reputation: 1192

You can extend the DropDownList and make it keep the list of objects in the session.

Like this:

DropDownListKeepRef:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;

namespace Q11456633WebApp
{
    /// <summary>
    /// Extension of <see cref="DropDownList"/> supporting reference to the 
    /// object related to the selected line.
    /// </summary>
    [ValidationProperty("SelectedItem")]
    [SupportsEventValidation]
    [ToolboxData(
      "<{0}:DropDownListKeepRef runat=\"server\"></{0}:DropDownListKeepRef>")]
    public class DropDownListKeepRef : DropDownList
    {
        protected override void PerformDataBinding(System.Collections.IEnumerable dataSource)
        {
            if (!String.IsNullOrEmpty(this.DataValueField))
            {
                throw new InvalidOperationException(
                    "'DataValueField' cant be define in this implementation. This Control use the index of list");
            }

            this.Items.Clear();
            ArrayList list = new ArrayList();
            int valueInt = 0;
            if (this.FirstNull)
            {
                list.Add(null);
                this.Items.Add(new ListItem(this.FirstNullText, valueInt.ToString()));
                valueInt++;
            }
            foreach (object item in dataSource)
            {
                String textStr = null;
                if (item != null)
                {
                    Object textObj = item.GetType().GetProperty(this.DataTextField).GetValue(item, null);
                    textStr = textObj != null ? textObj.ToString() : "";
                }
                else
                {
                    textStr = "";
                }

                //montando a listagem
                list.Add(item);
                this.Items.Add(new ListItem(textStr, valueInt.ToString()));
                valueInt++;
            }
            this.listOnSession = list;
        }

        private bool firstNull = false;
        /// <summary>
        /// If <c>true</ c> include a first line that will make reference to <c>null</c>,
        /// otherwise there will be only the line from the DataSource.
        /// </summary>
        [DefaultValue(false)]
        [Themeable(false)]
        public bool FirstNull
        {
            get
            {
                return firstNull;
            }
            set
            {
                firstNull = value;
            }
        }

        private string firstNullText = "";
        /// <summary>
        /// Text used if you want a first-line reference to <c>null</c>.
        /// </summary>
        [DefaultValue("")]
        [Themeable(false)]
        public virtual string FirstNullText
        {
            get
            {
                return firstNullText;
            }
            set
            {
                firstNullText = value;
            }
        }

        /// <summary>
        /// List that keeps the object instances.
        /// </summary>
        private IList listOnSession
        {
            get
            {
                return this.listOfListsOnSession[this.UniqueID + "_listOnSession"];
            }
            set
            {
                this.listOfListsOnSession[this.UniqueID + "_listOnSession"] = value;
            }
        }

        #region to avoid memory overload
        private string currentPage
        {
            get
            {
                return (string)HttpContext.Current.Session["DdlkrCurrentPage"];
            }
            set
            {
                HttpContext.Current.Session["DdlkrCurrentPage"] = value;
            }
        }

        /// <summary>
        /// Every time you change page, lists for the previous page will be 
        /// discarded from memory.
        /// </summary>
        private IDictionary<String, IList> listOfListsOnSession
        {
            get
            {
                if (currentPage != this.Page.Request.ApplicationPath)
                {
                    currentPage = this.Page.Request.ApplicationPath;
                    HttpContext.Current.Session["DdlkrListOfListsOnSession"] = new Dictionary<String, IList>();
                }
                if (HttpContext.Current.Session["DdlkrListOfListsOnSession"] == null)
                {
                    HttpContext.Current.Session["DdlkrListOfListsOnSession"] = new Dictionary<String, IList>();
                }

                return (IDictionary<String, IList>)HttpContext.Current.Session["DdlkrListOfListsOnSession"];
            }
        } 
        #endregion

        public Object SelectedObject
        {
            get
            {
                if (this.SelectedIndex > 0 && this.listOnSession.Count > this.SelectedIndex)
                    return this.listOnSession[this.SelectedIndex];
                else
                    return null;
            }
            set
            {
                if (!this.listOnSession.Contains(value))
                {
                    throw new IndexOutOfRangeException(
                        "Objeto nao contido neste 'DropDownListKeepRef': " +
                        value != null ? value.ToString() : "<null>");
                }
                else
                {
                    this.SelectedIndex = this.listOnSession.IndexOf(value);
                }
            }
        }

        /// <summary>
        /// List of related objects.
        /// </summary>
        public IList Objects
        {
            get
            {
                return new ArrayList(this.listOnSession);
            }
        }

        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protected override void LoadViewState(object savedState)
        {
            object[] totalState = null;
            if (savedState != null)
            {
                totalState = (object[])savedState;
                if (totalState.Length != 3)
                {
                    throw new InvalidOperationException("View State Invalida!");
                }
                // Load base state.
                int i = 0;
                base.LoadViewState(totalState[i++]);
                // Load extra information specific to this control.
                this.firstNull = (bool)totalState[i++];
                this.firstNullText = (String)totalState[i++];
            }
        }

        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protected override object SaveViewState()
        {
            object baseState = base.SaveViewState();
            object[] totalState = new object[3];
            int i = 0;
            totalState[i++] = baseState;
            totalState[i++] = this.firstNull;
            totalState[i++] = this.firstNullText;
            return totalState;
        }
    }
}

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Q11456633WebApp._Default" %>

<%@ Register Assembly="Q11456633WebApp" Namespace="Q11456633WebApp" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <cc1:DropDownListKeepRef ID="ListofDatesDdlkr" runat="server" AutoPostBack="True" DataTextField="Date" OnSelectedIndexChanged="ListofDatesDdlkr_SelectedIndexChanged">
        </cc1:DropDownListKeepRef>&nbsp;</div>
    </form>
</body>
</html>

Default.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Q11456633WebApp
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.ListofDatesDdlkr.DataSource = this.ListOfDate;
                this.ListofDatesDdlkr.DataBind();
            }
        }

        private DateTime[] ListOfDate
        {
            get
            {
                return new DateTime[]
                {
                    new DateTime(2012, 7, 1),
                    new DateTime(2012, 7, 2),
                    new DateTime(2012, 7, 3),
                    new DateTime(2012, 7, 4),
                    new DateTime(2012, 7, 5),
                };
            }
        }

        protected void ListofDatesDdlkr_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ClientScript.RegisterStartupScript(
                this.GetType(), 
                "show_type", 
                String.Format(
                    "alert('Type of SelectedObject:{0}')", 
                    this
                        .ListofDatesDdlkr
                            .SelectedObject
                                .GetType()
                                    .FullName), 
                    true);
        }
    }
}

Solution with the complete sample code: Q11456633WebApp.7z

Upvotes: 0

mgnoonan
mgnoonan

Reputation: 7200

The DropDownList doesn't actually store the entire object during the binding, only the Text and Value as defined by DataTextField and DataValueField. In order to get a selected object back, you are going to have to store the entire list of objects locally in the page (such as in ViewState). You'll also have to come up with your own DropDownList implementation to handle marshalling the list to and from local storage.

I think it would be simpler to cache the list locally (to save yourself a trip back to the database) and just do the lookup using the SelectedValue.

Upvotes: 4

Adil
Adil

Reputation: 148150

Web dropdownlist is not like the window forms combo to bind it with class. It has collection of ListItems which has Value and Text. So you can only get Text or Value from it. More about DropDownList

Upvotes: 1

Andre Calil
Andre Calil

Reputation: 7692

Patrick, looking at this history, looks like you can't do that without creating a custom dropdownlist

Regards

Upvotes: 1

Related Questions