1

我有一个自定义 DropDownList 控件:

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

DropDownList 有一个名为 DefaultCountry 的自定义属性。如您所见,默认值设置为“美国”。但是在我的子类中, 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
}
4

2 回答 2

0

解决方案是不在构造函数中绑定数据,而是从我页面后面的代码中调用它。在控件上调用 RenderControl 方法之前,似乎不会设置属性的值(例如 @DefaultCountry)。

于 2012-01-29T14:06:35.730 回答
0

您需要对Selected property 要将其设置为默认值的项目使用 true 。在此处查找示例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
于 2012-01-28T19:49:15.950 回答