2

ドロップダウンリストを地域ごとにグループ化する必要のある国とバインドする必要があります。次のリンクからサンプルコードを見つけました。

http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx?msg=3984074#xx3984074xx

これと同じ国リストが欲しかった。しかし、問題は、SQL結果からドロップダウンリストをバインドしたいということです。私は次のことを試しましたが、うまくいきませんでした、

ddlCountry.DataSource = CountryDtoCollection;
ddlCountry.DataBind();
ddlCountry.Attributes.Add("OptionGroup", "Region");

誰もがこれに対する解決策を知っています。

4

1 に答える 1

4

カスタムサーバーコントロールを記述し、|で区切られたテキストと領域を含むデータソースウィッチを使用できます。その後、使用時に分割します。

[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");
            }

        }
    }
}
于 2011-08-06T12:01:00.357 に答える