Programming Tutorials

Name Value Collecion in VB.net

By: Issac in VB.net Tutorials on 2009-01-30  

NameValueCollection is a class in VB.net that is used to represent a collection of associated String keys and String values that can be accessed either with the key or with the index. It is similar to a Dictionary, but allows for duplicate keys.

To use the NameValueCollection class, you first need to import the System.Collections.Specialized namespace. Then you can create an instance of the NameValueCollection and add items to it using the Add method. Here's an example:

Imports System.Collections.Specialized

' ...

Dim myCollection As New NameValueCollection()
myCollection.Add("key1", "value1")
myCollection.Add("key2", "value2")
myCollection.Add("key1", "value3") ' Adding duplicate key

' Accessing values by key
Dim value1 As String = myCollection("key1")
Dim value2 As String = myCollection("key2")

' Accessing values by index
Dim value3 As String = myCollection(0)
Dim value4 As String = myCollection(1)

' Looping through all keys and values
For Each key As String In myCollection.AllKeys
    Console.WriteLine("Key: " & key)
    For Each value As String In myCollection.GetValues(key)
        Console.WriteLine("Value: " & value)
    Next
Next

In this example, we create a new NameValueCollection called myCollection, and add three items to it using the Add method. The first two items have unique keys, but the third item has a duplicate key.

We can access values in the collection using either the key or the index. In this example, we retrieve the values of the first two items using their keys, and the values of the last two items using their indexes.

Finally, we loop through all the keys in the collection using the AllKeys property, and use the GetValues method to retrieve all the values associated with each key. This allows us to print out all the key-value pairs in the collection.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in VB.net )

Latest Articles (in VB.net)