Web User Controls: Exposing Items property of contained controls

W

Warped

I am trying to make a simple user control that contains a Label and a
DropDownList. Basically, I want this control to expose some of the
Label's properties (e.g. Text) and some of the DropDownList's
properties (e.g. Items) and have the designer handle them
appropriately. Exposing Label.Text wasn't a problem, but I can't get
DropDownList.Items to work. I added an Items property to my codebhind
class like this.

public partial class LabelledDropDown : System.Web.UI.UserControl
{

public ListItemCollection Items
{
get { return this.DropDownList1.Items; }
}
}

When I place an instance of the user control on a web form, the Items
property does appear in the designer, but the designer doesn't treat it
as an editable collection. How do I make that happen?

Also, any items I add to the collection via the designer should be
"remembered" in the .aspx file as nested elements, like this.

<uc1:LabelledDropDown ID="LabelledDropDown1" runat="server"
LabelText="Screen size">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
</uc1:LabelledDropDown>

This functionality would be relatively simple in .NET WinForms, so I
assume it can be done in WebForms as well.
 
J

Jonathan Mast

Hi Warped,

In your code where you expose the nested DropDownLists Items collection, do
you define a setter?

I'll admit that I've never run into this situation, but that may very well
be your issue.

Try making this code:

public ListItemCollection Items
{
get { return this.DropDownList1.Items; }
}

Look like this:

public ListItemCollection Items
{
get{ return this.DropDownList1.Items; }
set{ this.DropDownList1.Items=value; }
}

Maybe that will make it work for you?

It seems to me that the reason the IDE does not treat it as an editable
collection is because if you don't provide a setter method to a property,
then it is effectively read-only.

Hope it helps.
 
W

Warped

A setter like that would allow me to replace the entire collection with
a new collection, but that's not what I want. I want to be able to
add/remove individual items to/from the collection. In other words,

MyControl.Items.Add(newItem);

not

MyControl.Items = NewCollectionOfItems;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top