我想要一個解決方案來實現一個屬性(或方法)來返回選定的對象。DropDownList返回一個對象,不僅是一個ID值
例子:
DropDownListUser.DataSource = UserList;
User user = (User)DropDownListUser.SelectedObject;
這可能嗎?
我想要一個解決方案來實現一個屬性(或方法)來返回選定的對象。DropDownList返回一個對象,不僅是一個ID值
例子:
DropDownListUser.DataSource = UserList;
User user = (User)DropDownListUser.SelectedObject;
這可能嗎?
帕特里克,看着這段歷史,就像你不能這樣做,而無需創建一個自定義的下拉列表
問候
網絡dropdownlist
是not like
該窗口形成combo
將其與類綁定。它具有ListItems
的集合,其具有Value
和Text
。所以你只能從中獲取文本或數值。更多信息DropDownList
DropDownList
在綁定過程中實際上並不存儲整個對象,只有文本和值由DataTextField
和DataValueField
定義。爲了獲取選定的對象,您必須在頁面中本地存儲整個對象列表(例如ViewState
)。你還必須拿出你自己的DropDownList
實現來處理列表和本地存儲之間的列表。
我認爲在本地緩存列表會比較簡單(爲了節省自己的時間回到數據庫),只需使用SelectedValue
進行查找即可。
您可以擴展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;
}
}
}
的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> </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);
}
}
}
帶有完整示例代碼的解決方案:Q11456633WebApp.7z
儘管ASP .NET很神奇,但Web是無狀態的。您所需要的只是選定的「Value」屬性。在回發期間,您應該能夠根據該值找到對象。無論如何,這是它的目的。 – Yuck 2012-07-12 16:55:47