473,558 Members | 2,949 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help deleting a member of an enumeration from within a loop

Tim
Hi,
I'm very new to .NET and am programming in C#. I have a web application
where i have two list boxes. Its kind of like a shopping card where you can
add items from one 'locations' list box to the 'locations selected' (cart)
listbox. I have a hirarchy of locations - main locations and sub
locations. main locations being the parent locations, and the sub locations
being the child locations.

I want to be able to check to see if the already selected locations listbox
(cart) already contains a child location of a parent location that is trying
to be added to the collection (because there is no need to add the child
there if the parent is selected). if so the child should be deleted and the
parent added
I am looping through the locations selected, and for each one looping
through the already selected (cart) locations collection and checking the
existance of the members.
here is the code:

private void Button1_Click(o bject sender, System.EventArg s e)
{
if(lstLocations .SelectedIndex != -1)
{
foreach(ListIte m selectedLocatio n in lstLocations.It ems)
{
if(selectedLoca tion.Selected)
{
bool itemAlreadyExis ts = false;
bool parentItemExist s = false;
bool childItemExists = false;
foreach(ListIte m locationsSelect ed in
lstCart.Items)
{
//does new location already exist in
locations collection?

if(selectedLoca tion.Text.Equal s(locationsSele cted.Text.ToStr ing()))
{
itemAlreadyExis ts = true;
lblNotice.Text += "At least one of
the selected items already exists and has been ignored<br>";
}
if(!itemAlready Exists)
{

//does parent of child already exist
in collection

if(selectedLoca tion.Value.Star tsWith(location sSelected.Value .ToString()+"-")
)
{
parentItemExist s = true;
lblNotice.Text += "You
attempted to add a child location of a parent already selected. There is no
need to add a child location when the parent is already in your collection.
Item ignored<br>";
}
//does child of parent already exist
in collection, if so get rid of it
//this is the bit that is giving the
error!

if(locationsSel ected.Value.Sta rtsWith(selecte dLocation.Value .ToString()+"-")
)
{
childItemExists = true;

lstCart.Items.R emove(locations Selected); //this is where the error
occurs

lstCart.Items.A dd(selectedLoca tion);
lblNotice.Text += "A child
location was removed because you added its parent!<br>";
}
}

}
if(!itemAlready Exists && !parentItemExis ts &&
!childItemExist s)
{
lstCart.Items.A dd(selectedLoca tion);
}
}
}
}

}
when i execute the page and try add a parent location when a child already
exists the page throws the following error:

Collection was modified; enumeration operation may not execute.

I know this is pretty much saying that as the loop progresses, the code
tries to delete a member of the collection and hence modify the loop.
Can you see what i am trying to achieve and please advise me of the best way
around this problem?

Thanks alot for your help

Tim..
Nov 17 '05 #1
1 1691
Hi Tim

You can try two things:

Create an array. Add the items you want to remove from the list box to the
array. Then after the loop remove them.
Else --- This will be more efficent, but may be error prone; You need to
think about what will happen if you delete the last item...?

Use an old style loop, e.g.

for (int i=0; i<lstLocations. Items.Count; i++)
{
ListItem selectedLocatio n = lstLocations.It ems[i];

Then when you delete, deceriment i.

lstCart.Items.R emove(locations Selected);
i--;

Gary

"Tim" <ti***@broadban ned.net> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Hi,
I'm very new to .NET and am programming in C#. I have a web application
where i have two list boxes. Its kind of like a shopping card where you can add items from one 'locations' list box to the 'locations selected' (cart)
listbox. I have a hirarchy of locations - main locations and sub
locations. main locations being the parent locations, and the sub locations being the child locations.

I want to be able to check to see if the already selected locations listbox (cart) already contains a child location of a parent location that is trying to be added to the collection (because there is no need to add the child
there if the parent is selected). if so the child should be deleted and the parent added
I am looping through the locations selected, and for each one looping
through the already selected (cart) locations collection and checking the
existance of the members.
here is the code:

private void Button1_Click(o bject sender, System.EventArg s e)
{
if(lstLocations .SelectedIndex != -1)
{
foreach(ListIte m selectedLocatio n in lstLocations.It ems) {
if(selectedLoca tion.Selected)
{
bool itemAlreadyExis ts = false;
bool parentItemExist s = false;
bool childItemExists = false;
foreach(ListIte m locationsSelect ed in
lstCart.Items)
{
//does new location already exist in
locations collection?

if(selectedLoca tion.Text.Equal s(locationsSele cted.Text.ToStr ing()))
{
itemAlreadyExis ts = true;
lblNotice.Text += "At least one of
the selected items already exists and has been ignored<br>";
}
if(!itemAlready Exists)
{

//does parent of child already exist in collection

if(selectedLoca tion.Value.Star tsWith(location sSelected.Value .ToString()+"-") )
{
parentItemExist s = true;
lblNotice.Text += "You
attempted to add a child location of a parent already selected. There is no need to add a child location when the parent is already in your collection. Item ignored<br>";
}
//does child of parent already exist in collection, if so get rid of it
//this is the bit that is giving the error!

if(locationsSel ected.Value.Sta rtsWith(selecte dLocation.Value .ToString()+"-") )
{
childItemExists = true;

lstCart.Items.R emove(locations Selected); //this is where the error
occurs

lstCart.Items.A dd(selectedLoca tion);
lblNotice.Text += "A child
location was removed because you added its parent!<br>";
}
}

}
if(!itemAlready Exists && !parentItemExis ts && !childItemExist s)
{
lstCart.Items.A dd(selectedLoca tion);
}
}
}
}

}
when i execute the page and try add a parent location when a child already
exists the page throws the following error:

Collection was modified; enumeration operation may not execute.

I know this is pretty much saying that as the loop progresses, the code
tries to delete a member of the collection and hence modify the loop.
Can you see what i am trying to achieve and please advise me of the best way around this problem?

Thanks alot for your help

Tim..

Nov 17 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
6986
by: Matthew Wells | last post by:
I'm using this code to delete all relationships in my mdb file iFlag = 1 Do While iFlag <> 0 iFlag = 0 For Each rel In db.Relations db.Relations.Delete rel.Name iFlag = 1 Next rel Loop
4
3038
by: Chris | last post by:
I've lurked around long enough... Time to interract =) I'm trying to make sense of the following. I can't quite wrap my head around what this is actually doing: ------------- typedef enum { DOUBLE_LIST, INT_LIST } DATA_TYPE; typedef struct { DATA_TYPE type;
6
1714
by: Dmitry Karneyev | last post by:
Hi! I try to delete rows from the table in such way foreach(DataRow row in MyDataSet.MyTable) { row.Delete(); } and recive an error that collection is changed and enumeration is impossible. I guesss that foraech operator uses collection of undeleted rows and this
0
952
by: Sean Flook | last post by:
I have got some code that can be called from 3 separate places and it works fine for 2 of them, but for the third it gives me the following exception System.InvalidOperationException in System.Windows.forms.dll Collection was modified; enumeration operation may not execute. There is no call stack associated with the exception. From...
4
5648
by: Marshal | last post by:
Sure... IEnumerable was inconvenient suggesting a separate class to service the enumeration, IEnumerator, and multiple operations: Current, MoveNext, Reset. (I'll warp the definition of "operation" for a second if you don't mind). However, it existed within intuitive language semantics, whereas the new "yield" keyword, while highly...
2
1170
by: rh0dium | last post by:
Hi all, Why doesn't this work as expected.. I expect that the the lines within the sections will get modified - permanently. It is modifying them during the first section but they never get saved to the new values.. Can anyone help me and even better explain why it's not working.. for section in self.sections: nidx = 0
6
1898
by: Yan | last post by:
Here is the code: class A {}; void (A::*A) (); // Line 3 int main() { A a; // Line 6 return 0; }
10
2067
by: braratine | last post by:
Hello, I have to following issue. A type is declared based on an enum: " enum TpAddressPlan { P_ADDRESS_PLAN_NOT_PRESENT = 0, P_ADDRESS_PLAN_UNDEFINED = 1, P_ADDRESS_PLAN_IP = 2, P_ADDRESS_PLAN_MULTICAST = 3, P_ADDRESS_PLAN_UNICAST = 4,
2
2968
by: StevenChiasson | last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller. This is more or less, your standard dynamic address book program. Adding, and listing work just fine. However, deleting, editing and viewing relies on member function retAddress....
0
7629
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7549
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7835
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8061
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7593
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6183
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.