Groups | Blog | Home
all groups > asp.net building controls > march 2004 >

asp.net building controls : Removing dynamic items from dropdownlist


Dominic
3/25/2004 4:58:16 PM
I've created a control inheriting from dropdownlist. What I need is a
RemoveDynamicItems method that would remove only list items that were
added programatically. Keeping all list items existing explicitly in
the designer (aspx file). Any ideas?


*** Sent via Developersdex http://www.developersdex.com ***
Victor Garcia Aprea [MVP]
3/26/2004 2:15:41 AM
Hi Dominic,

Hummm... after an item has been inserted I don't think there is an easy way
to differentiate if it was defined at design-time or it has added at
runtime. But if you're subclassing DropDownList you can try something like
this:

a) keep a private collection of items that you will fill at OnInit based on
the items that were declared at design-time.
b) add a public method "ResetToOriginalItems", I'm sure you can think of a
better name here ;-) -- in this method you should clear the original item
list and fill it with the list you created at OnInit time thus reverting the
list to the original items specified at design-time.

In code this should look something like this:
[C#]
protected override void OnInit(EventArgs e) {
foreach (ListItem ite in base.Items)
_items.Add (ite);
base.OnInit (e);
}

public void ResetToOriginalItems () {
this.Items.Clear ();
foreach (ListItem ite in _items)
this.Items.Add (ite);
}

This may work for you if you can live with the few assumptions made (no
items will be inserted before OnInit) but it should serve as a good
jumpstart...

--
Victor Garcia Aprea
Microsoft MVP | ASP.NET
Looking for insights on ASP.NET? Read my blog:
http://obies.com/vga/blog.aspx
To contact me remove 'NOSPAM'. Please post all questions to the newsgroup

[quoted text, click to view]

Dominic
3/26/2004 3:00:31 AM
Honestly, that thought had occured to me. I would consider it more than
a reasonable solution, and I'll probably program it as such. However,
I'm more of a purist, and the "double tracking" of a separate
ListItemCollection irks me a bit. Seems with ASP.Net that there's got
to be a better way.

*** Sent via Developersdex http://www.developersdex.com ***
Matthew Burnside
3/26/2004 1:40:59 PM
It would be neat if you could subclass ListItem for your dynamic items and
then do a typecheck...but ListItem is sealed.

How about adding an attribute to the dynamic list items only and then
checking for it? This would require overriding RenderContents() in order to
get around the bug where attributes added to ListItems are not rendered
properly, but hey, you're already subclassing DropDownList... :)

[quoted text, click to view]

AddThis Social Bookmark Button