ASP.net ListItem Attributes 属性回传丢失的解决方案
该方法为网上整理
1. 新继承一个列表控件
新控件中重写两个方法:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI.WebControls; 6 7 namespace GetDateDome 8 { 9 public class ListBoxEx:ListBox 10 { 11 protected override object SaveViewState() 12 { 13 // create object array for Item count + 1 14 object[] allStates = new object[this.Items.Count + 1]; 15 16 // the +1 is to hold the base info 17 object baseState = base.SaveViewState(); 18 allStates[0] = baseState; 19 20 Int32 i = 1; 21 // now loop through and save each Style attribute for the List 22 foreach (ListItem li in this.Items) 23 { 24 Int32 j = 0; 25 string[][] attributes = new string[li.Attributes.Count][]; 26 foreach (string attribute in li.Attributes.Keys) 27 { 28 attributes[j++] = new string[] { attribute, li.Attributes[attribute] }; 29 } 30 allStates[i++] = attributes; 31 } 32 return allStates; 33 } 34 35 protected override void LoadViewState(object savedState) 36 { 37 if (savedState != null) 38 { 39 object[] myState = (object[])savedState; 40 41 // restore base first 42 if (myState[0] != null) 43 base.LoadViewState(myState[0]); 44 45 Int32 i = 1; 46 foreach (ListItem li in this.Items) 47 { 48 // loop through and restore each style attribute 49 foreach (string[] attribute in (string[][])myState[i++]) 50 { 51 li.Attributes[attribute[0]] = attribute[1]; 52 } 53 } 54 } 55 } 56 57 } 58 }
2 页面注册控件
1 <%@ Register assembly="GetDateDome" namespace="GetDateDome" tagprefix="my" %>
3 使用新控件
1 <my:ListBoxEx ID="lstUnselectCol" runat="server" Style="width: 100%;height:100%;" ></my:ListBoxEx>
1 //设置属性 2 ListItem p = new ListItem(i["Item"].ToString(), i["value"].ToString()); 3 p.Attributes.Add("type", i["type"].ToString()); 4 lstUnselectCol.Items.Add(p); 5 6 7 //获取属性 8 string msg = srcList.SelectedItem.Attributes["type"];
4 最后记着设置 EnableViewState="true"