Subclass DropdownList and get value of public attribute

502 Views Asked by At

I have a custom DropDownList control:

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

The DropDownList has a custom property called DefaultCountry. As you can see, the default value is set to "USA". However in my subclass, DefaultCountry is always null.

How do I get it to set the DefaultCountry to what is in the ASP.NET markup?

[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
}
2

There are 2 best solutions below

0
On

The solution was to not bind the data in the constructor, but call it from the code behind on my page. It appears that the value of the attributes (e.g. @DefaultCountry) is not set until the RenderControl method is called on the control.

1
On

you need to use Selected property to true for the item which you want to set it as default. look here for examplesDropdownlist

 // 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>

but in your case. you may try like this, i m not sure, but a guess.

 this.Selected=true