2011-08-06 18 views
2

私は地域によってグループ化されなければならないcoutriesでDropDownListコントロールをバインドする必要があり、私は次のリンクからサンプルコードを発見した、バインドDropDownListのSQLデータソースから

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

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

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

誰にでもこれに対する解決策はあります。

答えて

3

あなたはカスタムサーバーコントロールを作成し、テキストと地域を含むデータソースを使用することができます|その後、使用時に分割します。

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

     } 
    } 
} 
関連する問題