Collection class error

  • Thread starter Thread starter Lou
  • Start date Start date
L

Lou

I get an error when i try to enumerate through the list

SortedList Projects = new SortedList();


//Create a Project object
cProject Project = new cProject(mxDoc);
Project.Name = strFileName;
//Add the project object to a list of projects

Projects.Add(strFileName, Project);

//Enumerate through the list. This is where I get the error

foreach (cProject myProject in Projects)

{

this.treeView1.Nodes[0].Nodes.Add(myProject.Name);

}

System.InvalidCastException was unhandled
Message="Unable to cast object of type
'System.Collections.DictionaryEntry' to type
'InflexionTestHarness.cProject'."
 
I get an error when i try to enumerate through the list

SortedList Projects = new SortedList();

//Create a Project object
cProject Project = new cProject(mxDoc);
Project.Name = strFileName;
//Add the project object to a list of projects

Projects.Add(strFileName, Project);

//Enumerate through the list. This is where I get the error

foreach (cProject myProject in Projects)

{

this.treeView1.Nodes[0].Nodes.Add(myProject.Name);

}

System.InvalidCastException was unhandled
  Message="Unable to cast object of type
'System.Collections.DictionaryEntry' to type
'InflexionTestHarness.cProject'."

A SortedList is a dictionary-type object. It contains two
members, Keys and Values. The keys would map to the strFileName
in your above example, whereas the Values would be the objects
themselves.

So, what you want is:

foreach (cProject myProject in Projects.Values)

Matt
 
I get an error when i try to enumerate through the list

SortedList Projects = new SortedList();

//Create a Project object
cProject Project = new cProject(mxDoc);
Project.Name = strFileName;
//Add the project object to a list of projects

Projects.Add(strFileName, Project);

//Enumerate through the list. This is where I get the error

foreach (cProject myProject in Projects)

{

this.treeView1.Nodes[0].Nodes.Add(myProject.Name);

}

System.InvalidCastException was unhandled
  Message="Unable to cast object of type
'System.Collections.DictionaryEntry' to type
'InflexionTestHarness.cProject'."

From MSDN documentation for class SortedList:

"public class SortedList : IDictionary, ..."

"The foreach statement of the C# language (for each in Visual Basic)
requires the type of each element in the collection. Since each
element of the SortedList object is a key/value pair, the element type
is not the type of the key or the type of the value. Rather, the
element type is DictionaryEntry."
 
Back
Top