1

我想要一个解决方案来实现一个属性(或方法)来返回选定的对象。

例子:

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

这可能吗?

4

4 回答 4

4

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.

于 2012-07-12T16:51:32.353 回答
1

帕特里克,看着这段历史,看起来如果不创建自定义下拉列表就无法做到这一点

问候

于 2012-07-12T16:50:14.077 回答
1

Webdropdownlist是将其与类绑定not like的窗口形式。combo它有集合,ListItems其中有ValueText。所以你只能从中获取 Text 或 Value 。更多关于下拉列表

于 2012-07-12T16:50:32.767 回答
0

您可以扩展 DropDownList 并使其保留会话中的对象列表。

像这样:

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;
        }
    }
}

默认.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>

默认.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);
        }
    }
}

带有完整示例代码的解决方案:Q11456633WebApp.7z

于 2012-07-12T17:05:19.577 回答