2012-01-28 29 views
1

的獲得價值我有一個自定義DropDownList控件:子類下拉列表和公共屬性

<cc1:CountriesControl ID="DdlCountry" TabIndex="69" runat="server" DefaultCountry="USA" OnSelectedIndexChanged="DdlCountryIndexChanged" 
           CssClass="DefaultDropdown" AutoPostBack="true" /> 

DropDownList控件有一個名爲DefaultCountry自定義屬性。如您所見,默認值設置爲「USA」。但是在我的子類中,DefaultCountry始終爲空。

如何獲取它以將DefaultCountry設置爲ASP.NET標記中的內容?

[DefaultProperty("Text"), ToolboxData("<{0}:CountriesControl runat=server></{0}:CountriesControl>")] 
public class CountriesControl : DropDownList 
{ 
    [Bindable(true), Category("Appearance"), DefaultValue("")] 

    private String defaultCountry; 
    [ 
    Category("Behavior"), 
    DefaultValue(""), 
    Description("Sets the default country"), 
    NotifyParentProperty(true) 
    ] 
    public String DefaultCountry 
    { 
     get 
     { 
      return defaultCountry; 
     } 
     set 
     { 
      defaultCountry = value; 
     } 
    } 

    public CountriesControl() 
    {       

     this.DataSource = CountriesDataSource(); 
     this.DataTextField = "CountryName"; 
     this.DataValueField = "Country"; 
     this.SelectedIndex = 0; 

     this.DataBind(); 

     // DefaultCountry is always null? 
     this.Items.Insert(0, new ListItem(this.DefaultCountry, "--")); 

    } 
// more code here 
} 

回答

0

您需要使用Selected property爲您想要將其設置爲默認項的項。看這裏爲例Dropdownlist

// this is the normal syntax. to get the default value for dropdownlist 
<asp:DropDownList ID="DropDownList1" runat="server" width="145px"> 

<asp:ListItem Text="SomeText" Value="SomeValue" Selected="true"></asp:ListItem> 

</asp:DropDownList> 

但在你的情況。你可以嘗試這樣,我不確定,但猜測。

this.Selected=true 
+0

感謝您的幫助。這是一個自定義控件。我想通過屬性@DefaultCountry設置默認值。它沒有被設置。 – PhillyNJ 2012-01-28 19:53:29

0

解決方案是不綁定構造函數中的數據,而是從我的頁面後面的代碼調用它。看來,屬性的值(例如@DefaultCountry)在控件上調用RenderControl方法之前不會被設置。