NameValueCollection with Example in C#
NameValueCollection collection is based on the NameObjectCollectionBase class. However, unlike the NameObjectCollectionBase, this class stores multiple string values under a single key.
This class can be used for headers, query strings and form data.
Each element is a key/value pair.
Collections of this type do not preserve the ordering of element, and no particular ordering is guaranteed when enumerating the collection.
The capacity of a NameValueCollection is the number of elements the NameValueCollection can hold. As elements are added to a NameValueCollection, the capacity is automatically increased as required through reallocation.
Aspx :
<table width="100%">
<tr>
<td align ="center">
<table width ="50%">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Using All Key"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvAllKey" runat="server">
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Using Get Key"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvGetKeyNGet" runat="server">
</asp:GridView>
</td>
</tr>
</table>
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
NameValueCollection myColl = new NameValueCollection();
myColl.Add("Kalyani", "1");
myColl.Add("Impact", "2");
myColl.Add("IBM", "3");
IList<ABC> anc = GetAllKeys(myColl);
IList<ABC> abc = GetKeys(myColl);
gvAllKey.DataSource = anc.AsEnumerable();
gvAllKey.DataBind();
gvGetKeyNGet.DataSource = abc.AsEnumerable();
gvGetKeyNGet.DataBind();
}
public IList<ABC> GetAllKeys(NameValueCollection coll)
{
IList<ABC> _list = new List<ABC>();
foreach (string item in coll.AllKeys)
{
ABC a = new ABC();
a.Name = item.ToString();
a.Value = coll[item].ToString();
_list.Add(a);
}
return _list;
}
public IList<ABC> GetKeys(NameValueCollection coll)
{
IList<ABC> _list = new List<ABC>();
for (int i = 0; i < coll.Count; i++)
{
ABC abc = new ABC();
abc.Name = coll.GetKey(i).ToString();
abc.Value = coll.Get(i).ToString();
_list.Add(abc);
}
return _list;
}
}
public class ABC
{
public string Name { get; set; }
public string Value { get; set; }
}
Comments
Post a Comment