c# - Flaw in ToolStripItemCollection.AddRange method? -


i convinced in implementation of toolstripitemcollection.addrange mistake:

i made windows forms application 2 menus, each 1 containing 2 items.

first menu

second menu

(excuse me, don't have enough reputation post images).

next, implement button click handler:

private void button1_click(object sender, eventargs e) {     menu1.dropdownitems.addrange(menu2.dropdownitems); } 

and system.argumentoutofrangeexception thrown.

i extremely curious why happening , decompiled toolstripitemcollection assembly ilspy. here saw:

public void addrange(toolstripitemcollection toolstripitems) {     if (toolstripitems == null)     {         throw new argumentnullexception("toolstripitems");     }     if (this.isreadonly)     {         throw new notsupportedexception(sr.getstring("toolstripitemcollectionisreadonly"));     }     using (new layouttransaction(this.owner, this.owner, propertynames.items))     {         int count = toolstripitems.count;         (int = 0; < count; i++)         {             this.add(toolstripitems[i]);         }     } } 

there nothing bothered about. let's toolstripitemcollection.add method:

public int add(toolstripitem value) {     this.checkcanaddorinsertitem(value);     this.setowner(value);     int result = base.innerlist.add(value);     if (this.itemscollection && this.owner != null)     {         this.owner.onitemadded(new toolstripitemeventargs(value));     }     return result; } 

and toolstripitemcollection.setowner:

private void setowner(toolstripitem item) {     if (this.itemscollection && item != null)     {         if (item.owner != null)         {             item.owner.items.remove(item);         }         item.setowner(this.owner);         if (item.renderer != null)         {             item.renderer.initializeitem(item);         }     } } 

we can see, loop delete item toolstripitems in every step. msdn puts remarks ilist interface toolstripitemcollection implements: in collections of contiguous elements, such lists, elements follow removed element move occupy vacated spot. if collection indexed, indexes of elements moved updated.. result, end accesing item in toolstripitems on wrong index (second item shifted position 0). right?

not 100% sure question is, can work around issue converting collection array (which requires cast):

menu1.dropdownitems.addrange(menu2.dropdownitems.cast<toolstripitem>().toarray()); 

your version throwing error because when first menu gets added dropdown collection, getting removed collection iterating over, hence outofrangeexception.


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -