2012-01-28 81 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方法之前不会被设置。