Bind Dropdownlist with optGroup from sql datasource

二次信任 提交于 2019-12-04 16:41:50

you can write a custom server control and use the data source witch containing the text and region separated by | then split it when use.

[ToolboxData("<{0}:CustomDropDownList runat=server></{0}:CustomDropDownList>")]
public class CustomDropDownList : DropDownList
{
    protected override void RenderContents(HtmlTextWriter writer)
    {
        if (this.Items.Count > 0)
        {
            bool selected = false;
            bool optGroupStarted = false;
            string lastOptionGroup = string.Empty;
            for (int i = 0; i < this.Items.Count; i++)
            {
                ListItem item = this.Items[i];
                if (item.Enabled)
                {
                    if (lastOptionGroup != item.Text.Split("|")[1])
                    {
                        if (optGroupStarted)
                        {
                            writer.WriteEndTag("optgroup");
                        }
                        lastOptionGroup = item.Text.Split("|")[1];
                        writer.WriteBeginTag("optgroup");
                        writer.WriteAttribute("label", lastOptionGroup);
                        writer.Write('>');
                        writer.WriteLine();
                        optGroupStarted = true;
                    }
                    writer.WriteBeginTag("option");
                    if (item.Selected)
                    {
                        if (selected)
                        {
                            this.VerifyMultiSelect();
                        }
                        selected = true;
                        writer.WriteAttribute("selected", "selected");
                    }
                    writer.WriteAttribute("value", item.Value, true);
                    if (item.Attributes.Count > 0)
                    {
                        item.Attributes.Render(writer);
                    }
                    if (this.Page != null)
                    {
                        this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);
                    }
                    writer.Write('>');
                    HttpUtility.HtmlEncode(item.Text.Split("|")[0], writer);
                    writer.WriteEndTag("option");
                    writer.WriteLine();
                }
            }
            if (optGroupStarted)
            {
                writer.WriteEndTag("optgroup");
            }

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!