我必须绑定一个Dropdownlist,其中的coutries应按区域分组,我已从以下链接找到示例代码,
http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx?msg=3984074#xx3984074xx
我希望国家/地区列表与此相同。但问题是我想从sql结果中绑定下拉列表。我尝试了以下但没有奏效,
ddlCountry.DataSource = CountryDtoCollection;
ddlCountry.DataBind();
ddlCountry.Attributes.Add("OptionGroup", "Region");
任何人都知道任何解决方案。
答案 0 :(得分: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");
}
}
}
}