post icon

C Sharp DropDownList extender for programmatically Option Group

Questo snippet estende in C# il controllo DropDownList per aggiungere dinamicamente l'option group in modo che il risultato finale sia il seguente:

Ecco l'extender:

public class DropDownListAdapter : System.Web.UI.WebControls.Adapters.WebControlAdapter { protected override void RenderContents(HtmlTextWriter wr) { DropDownList list = this.Control as DropDownList; string currentOptGroup; List<string> renderedOptGroups = new List<string>(); foreach (ListItem item in list.Items) { if (item.Attributes["OptionGroup"] == null) { RenderListItem(item, wr); } else { currentOptGroup = item.Attributes["OptionGroup"]; if (renderedOptGroups.Contains(currentOptGroup)) { RenderListItem(item, wr); } else { if (renderedOptGroups.Count > 0) { RenderOptionGroupEndTag(wr); } RenderOptionGroupBeginTag(currentOptGroup, wr); renderedOptGroups.Add(currentOptGroup); RenderListItem(item, wr); } } } if (renderedOptGroups.Count > 0) { RenderOptionGroupEndTag(wr); } } private void RenderOptionGroupBeginTag(string name, HtmlTextWriter wr) { wr.WriteBeginTag("optgroup"); wr.WriteAttribute("label", name); wr.Write(HtmlTextWriter.TagRightChar); wr.WriteLine(); } private void RenderOptionGroupEndTag(HtmlTextWriter wr) { wr.WriteEndTag("optgroup"); wr.WriteLine(); } private void RenderListItem(ListItem item, HtmlTextWriter wr) { wr.WriteBeginTag("option"); wr.WriteAttribute("value", item.Value, true); if (item.Selected) { wr.WriteAttribute("selected", "selected", false); } foreach (string key in item.Attributes.Keys) { wr.WriteAttribute(key, item.Attributes[key]); } wr.Write(HtmlTextWriter.TagRightChar); HttpUtility.HtmlEncode(item.Text, wr); wr.WriteEndTag("option"); wr.WriteLine(); } }

Download DropDownList_OptionGroup.zip (9,58 kb)

17 febbraio 2009 @ 19:00

No comments yet.

Leave a comment

Leave a Reply

Are you human? Time limit is exhausted. Please reload CAPTCHA.