1: public class GroupedDropDownList : DropDownList
2: {
3: public String DataOptionGroupField
4: {
5: get;
6: set;
7: }
8:
9: protected override void PerformDataBinding(IEnumerable dataSource)
10: {
11: base.PerformDataBinding(dataSource);
12:
13: if ((String.IsNullOrWhiteSpace(this.DataOptionGroupField) == false) && (dataSource != null))
14: {
15: ListItemCollection items = this.Items;
16: IEnumerable<Object> data = dataSource.OfType<Object>();
17: Int32 count = data.Count();
18:
19: for (Int32 i = 0; i < count; ++i)
20: {
21: String group = DataBinder.Eval(data.ElementAt(i), this.DataOptionGroupField) as String ?? String.Empty;
22:
23: if (String.IsNullOrWhiteSpace(group) == false)
24: {
25: items[i].Attributes["Group"] = group;
26: }
27: }
28: }
29: }
30:
31: protected override void RenderContents(HtmlTextWriter writer)
32: {
33: ListItemCollection items = this.Items;
34: Int32 count = items.Count;
35: var groupedItems = items.OfType<ListItem>().GroupBy(x => x.Attributes["Group"] ?? String.Empty).Select(x => new { Group = x.Key, Items = x.ToList() });
36:
37: if (count > 0)
38: {
39: Boolean flag = false;
40:
41: foreach (var groupedItem in groupedItems)
42: {
43: if (String.IsNullOrWhiteSpace(groupedItem.Group) == false)
44: {
45: writer.WriteBeginTag("optgroup");
46: writer.WriteAttribute("label", groupedItem.Group);
47: writer.Write('>');
48: }
49:
50: for (Int32 i = 0; i < groupedItem.Items.Count; ++i)
51: {
52: ListItem item = groupedItem.Items[i];
53:
54: if (item.Enabled == true)
55: {
56: writer.WriteBeginTag("option");
57:
58: if (item.Selected == true)
59: {
60: if (flag == true)
61: {
62: this.VerifyMultiSelect();
63: }
64:
65: flag = true;
66:
67: writer.WriteAttribute("selected", "selected");
68: }
69:
70: writer.WriteAttribute("value", item.Value, true);
71:
72: if (item.Attributes.Count != 0)
73: {
74: item.Attributes.Render(writer);
75: }
76:
77: if (this.Page != null)
78: {
79: this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);
80: }
81:
82: writer.Write('>');
83: HttpUtility.HtmlEncode(item.Text, writer);
84: writer.WriteEndTag("option");
85: writer.WriteLine();
86: }
87: }
88:
89: if (String.IsNullOrWhiteSpace(groupedItem.Group) == false)
90: {
91: writer.WriteEndTag("optgroup");
92: }
93: }
94: }
95: }
96: }