How to VB.Net NameValueCollection

The NameValueCollection class is a collection that stores a collection of associated key-value pairs, where each key can have multiple values. It provides a convenient way to work with data that requires a mapping between keys and their corresponding values.

Important functions in VB.Net NameValueCollection

The NameValueCollection class is part of the System.Collections.Specialized namespace. Here are some important features and examples of using the NameValueCollection class:

Adding Key-Value Pairs

You can add key-value pairs to a NameValueCollection using the Add method. Keys are unique, but values can be duplicated.

Dim collection As New NameValueCollection() collection.Add("Key1", "Value1") collection.Add("Key2", "Value2") collection.Add("Key2", "Value3")

Accessing Values by Key

You can access the values associated with a specific key using the indexer (Item) property.

Dim collection As New NameValueCollection() collection.Add("Key1", "Value1") collection.Add("Key2", "Value2") collection.Add("Key2", "Value3") Dim value As String = collection("Key2")

Getting All Keys

You can retrieve all the keys present in the NameValueCollection using the AllKeys property.

Dim collection As New NameValueCollection() collection.Add("Key1", "Value1") collection.Add("Key2", "Value2") collection.Add("Key2", "Value3") Dim keys() As String = collection.AllKeys

Modifying Values

You can modify the values associated with a specific key using the indexer (Item) property.

Dim collection As New NameValueCollection() collection.Add("Key1", "Value1") collection("Key1") = "NewValue"

Removing Key-Value Pairs

You can remove key-value pairs using the Remove method.

Dim collection As New NameValueCollection() collection.Add("Key1", "Value1") collection.Add("Key2", "Value2") collection.Remove("Key1")

The provided VB.NET source code showcases a selection of frequently utilized functions.

Full Source VB.NET
Imports System.Collections.Specialized Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim markStatus As New NameValueCollection Dim key As String Dim values() As String markStatus.Add("Very High", "80") markStatus.Add("High", "60") markStatus.Add("medium", "50") markStatus.Add("Pass", "40") For Each key In markStatus.Keys values = markStatus.GetValues(key) For Each value As String In values MsgBox(key & " - " & value) Next value Next key End Sub End Class

Conclusion

The NameValueCollection class provides a useful data structure for managing key-value pairs, especially when keys can have multiple associated values. It is commonly used for working with query string parameters, HTTP headers, and configuration settings.