iceheaven31
iceheaven31

Reputation: 887

An item with the same key has already been added error

I know the error is a common one but i'm not sure how to solve this.

my scenario is this:

Upvotes: 2

Views: 6486

Answers (1)

Samuel Slade
Samuel Slade

Reputation: 8613

It sounds like you are adding data to something in Window 2 that is shared across the entire application, or all instance of Window 2. When you enter Window 2 for a second time and populate your data, you are likely adding the data into a Dictionary that has already been added. Hence the message "An item with the same key has already been added".

My advice: put a break point in the code where you populate the data, and check the values contained within the Dictionary (if you have used one and have access to it). Then check the data you are adding and you should find the replication.

Alternately, there are various ways to prevent duplicate entries being added.

  1. Clean the Dictionary when you have finished with it the first time - this way you only add the data in once (unless you have duplicate entries in your source data).

  2. See if the key exists within the Dictionary before adding the entry. You can do this by using if (mSomeDictionary.ContainsKey(someEntryKey))/

  3. If you simply want to use the latest values, you can just override the data keyed with a certain object. You can do this by using something like: mSomeDictionary[someEntryKey] = someValue;. If the entry key doesn't already exist, a new entry will automatically be added.

If none of the above helps you at all, post the code where the error occurs and include the Stack Trace from within the thrown exception and we can look into it further.

Upvotes: 4

Related Questions