Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use C# NameValueCollection Class



NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the Key or with the index. It is very similar to C# Hashtable; HashTable also stores data in Key, value format.

NameValueCollection can hold multiple string values under a single key. As elements are added to a NameValueCollection, the capacity is automatically increased as required through reallocation. The one important thing is that you have to import System.Collections.Specialized Class in your program for using NameValueCollection.

Adding new pairs

NameValueCollection.Add(name,value)
NameValueCollection pair = new NameValueCollection();
pair.Add("High", "80");

Get the value of the corresponding Key

string[] NameValueCollection.GetValues(index);
NameValueCollection pair = new NameValueCollection();
pair.Add("High", "80");
string[] vals = pair.GetValues(1);
using System;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NameValueCollection markStatus = new NameValueCollection();
            string[] values = null;

            markStatus.Add("Very High", "80");
            markStatus.Add("High", "60");
            markStatus.Add("medium", "50");
            markStatus.Add("Pass", "40");

            foreach (string key in markStatus.Keys)
            {
                values = markStatus.GetValues(key);
                foreach (string value in values)
                {
                    MessageBox.Show (key + " - " + value);
                }
            } 
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More