① Create a new Webusercontrol1.ascx user control, in order to be simple, we put a DropDownList control directly in the control. If we do not add any properties for the Webusercontrol1.ascx control, it is not possible to add a Drop-down item to the DropDownList control outside the control.
② Now we add an items property to the Webusercontrol1.ascx control that maps directly to the DropDownList items property as follows:
The code is as follows |
Copy Code |
Public ListItemCollection Items { get {return this. Dropdownlist1.items; } }
|
So, in the CS file that calls the ASPX page of the user control, you can programmatically add a Drop-down item to the DropDownList control, as follows:
The code is as follows |
Copy Code |
protected void Page_Load (object sender, EventArgs e) { This. WEBUSERCONTROL11.ITEMS.ADD (New ListItem ("Bank of China", "0")); }
|
But at this point I can't add a Drop-down item directly to the DropDownList control in ASPX.
③ Now we add a property to the items property of the user control, the following code:
The code is as follows |
Copy Code |
[PersistenceMode (Persistencemode.innerdefaultproperty)] Public ListItemCollection Items { get {return this. Dropdownlist1.items; } }
|
Explain the meaning of the above code:
PersistenceMode: Defines a metadata attribute that specifies how to save a ASP.net server control property or event to an ASP at design time. NET page
Persistencemode.innerdefaultproperty: Specifies that the property is persisted as internal text in the ASP.net server control. It also indicates that the property is defined as the default property of the element. Only one property can be specified as the default property
④ only set this property, it is not enough, we also need to add a property for the user control class:
The code is as follows |
Copy Code |
[ParseChildren (True, "Items")] public partial class WebUserControl1:System.Web.UI.UserControl { }
|
ParseChildren: Defines the metadata properties that can be used when developing ASP.net server controls. Use the System.Web.UI.ParseChildrenAttribute class to indicate how the page parser should handle the nested contents of the server control tags declared on the page.