前段时间CSDN上的一个朋友问到DropDownList添加ListItem的时候在Attributes中添加了Style项,但实际浏览的时候确没有这个效果。后来我反编译了DropDownList看了一下,发觉DropDownList控件并没有把ListItem的Attributes进行输出。所以我从DropDownList派生出来重写了几个方法实现相关功能。代码如下:
public class MyDrop :DropDownList
{
protected override void RenderContents(HtmlTextWriter writer)
{
ListItemCollection listItemCollection = base.Items;
int i = base.Items.Count;
bool flag = false;
if (i > 0)
{
for (int j = 0; j < i; j++)
{
ListItem listItem = listItemCollection[j];
writer.WriteBeginTag("option");
if (listItem.Selected)
{
if (flag)
{
throw new HttpException("Cant_Multiselect_In_DropDownList");
}
flag = true;
writer.WriteAttribute("selected", "selected", false);
}
writer.WriteAttribute("value", listItem.Value, true);
System.Web.UI.AttributeCollection attributeCollection = listItem.Attributes;
IEnumerator iEnumerator = attributeCollection.Keys.GetEnumerator();
while (iEnumerator.MoveNext())
{
string str2 = (String)iEnumerator.Current;
writer.Write(" "+str2+"=/""+attributeCollection[str2]+"/"");
}
writer.Write('>');
HttpUtility.HtmlEncode(listItem.Text, writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}
}
protected override object SaveViewState()
{
object[] objs = new object[2];
objs[0]= base.SaveViewState ();
System.Collections.ArrayList list = new ArrayList();
objs[1]= list;
foreach(ListItem item in this.Items)
{
System.Collections.Hashtable hash = new Hashtable();
foreach(Object key in item.Attributes.Keys)
{
hash.Add(key,item.Attributes[key.ToString()]);
}
list.Add(hash);
}
return objs;
}
protected override void LoadViewState(object savedState)
{
object[] objs = (Object[])savedState;
base.LoadViewState (objs[0]);
System.Collections.ArrayList list = (System.Collections.ArrayList)objs[1];
for(int i =0;i< list.Count;i++)
{
System.Collections.Hashtable hash = (System.Collections.Hashtable)list[i];
foreach(object key in hash.Keys)
{
Items[i].Attributes.Add(key.ToString(),hash[key].ToString());
}
}
}
}