NameValueCollection ...

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
 
K

Konstantinos 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
 
S

shapper

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top