Pages

Saturday, July 7, 2012

How to use C# NameValueCollection Class


NameValueCollection is used to store a collection of associated String keys and String valuesthat 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.SpecializedClass 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 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);
                }
            } 
        }
    }
}

No comments:

Post a Comment