NameValueCollection ...

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I am having some problems in looping through each item in
NameValueCollection:

1 Dim a As New NameValueCollection
2 a.Add("My String", City.NewYork)
3 a.Add("My String", City.Paris)
4 a.Add("My String", City.London)
5
6 For Each b As KeyValuePair(Of String, City) In a
7 Response.Write(a.Key)
8 Response.Write(a.Value)
9 Next b

I get an error on code line 6:

"Specified cast is not valid."

What am I doing wrong?

Thanks,

Miguel
 
You're getting an error because NameValueCollection's add method takes two
parameters both of them being of type string.
Thus when you add "a.Add("My String", City.NewYork)" the collection contains
"My String" as key and "NewYork" (the ToString result of the City enymeration).
When you try to cast the second parameter to a City object on line 6 "KeyValuePair(Of
String, City)" it fails because it does not know how to do that.

HTH

Kostas Pantos
 
You're getting an error because NameValueCollection's add method takes two
parameters both of them being of type string.
Thus when you add "a.Add("My String", City.NewYork)" the collection contains
"My String" as key and "NewYork" (the ToString result of the City enymeration).
When you try to cast the second parameter to a City object on line 6 "KeyValuePair(Of
String, City)" it fails because it does not know how to do that.

HTH

Kostas Pantos

Hmmm,

How can I solve this?

I really need to use one of the items as an enumeration type.

I tried Dictionary which was working but it must have unique keys and
I need some repeating keys so I ended you trying NameValueCollection.

Any idea?

Thanks,
Miguel
 
shapper said:
Hello,

I am having some problems in looping through each item in
NameValueCollection:

1 Dim a As New NameValueCollection
2 a.Add("My String", City.NewYork)
3 a.Add("My String", City.Paris)
4 a.Add("My String", City.London)
5
6 For Each b As KeyValuePair(Of String, City) In a
7 Response.Write(a.Key)
8 Response.Write(a.Value)
9 Next b

I get an error on code line 6:

"Specified cast is not valid."

What am I doing wrong?

Thanks,

Miguel

You are creating a non-generic collection and try to use it as a generic
collection.

What you want is a generic dictionary:

Dim a As New Dictionary(Of String, City)

Now the rest of your code should work.
 
Back
Top