该方法为网上整理
1. 新继承一个列表控件
新控件中重写两个方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls; namespace GetDateDome
{
public class ListBoxEx:ListBox
{
protected override object SaveViewState()
{
// create object array for Item count + 1
object[] allStates = new object[this.Items.Count + ]; // the +1 is to hold the base info
object baseState = base.SaveViewState();
allStates[] = baseState; Int32 i = ;
// now loop through and save each Style attribute for the List
foreach (ListItem li in this.Items)
{
Int32 j = ;
string[][] attributes = new string[li.Attributes.Count][];
foreach (string attribute in li.Attributes.Keys)
{
attributes[j++] = new string[] { attribute, li.Attributes[attribute] };
}
allStates[i++] = attributes;
}
return allStates;
} protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
object[] myState = (object[])savedState; // restore base first
if (myState[] != null)
base.LoadViewState(myState[]); Int32 i = ;
foreach (ListItem li in this.Items)
{
// loop through and restore each style attribute
foreach (string[] attribute in (string[][])myState[i++])
{
li.Attributes[attribute[]] = attribute[];
}
}
}
} }
}
2 页面注册控件
<%@ Register assembly="GetDateDome" namespace="GetDateDome" tagprefix="my" %>
3 使用新控件
<my:ListBoxEx ID="lstUnselectCol" runat="server" Style="width: 100%;height:100%;" ></my:ListBoxEx>
//设置属性
ListItem p = new ListItem(i["Item"].ToString(), i["value"].ToString());
p.Attributes.Add("type", i["type"].ToString());
lstUnselectCol.Items.Add(p); //获取属性
string msg = srcList.SelectedItem.Attributes["type"];
4 最后记着设置 EnableViewState="true"