Prevent an error While adding same key in HashTable

Akiii
Posted by Akiii under C# category on | Points: 40 | Views : 2241
A HashTabe items are key-value pair, so to add the item you should have a unique key and a value. Before adding a pair to hashtable just check if key already exist and if exist do not insert it otherwise it will through a exception.

Suppose you already have a hashtable :-

Hashtable EmpHashTable = new EmpHashTable();
EmpHashTable.Add("Key1", "Akiii");
EmpHashTable.Add("Key2", "Sharad");
EmpHashTable.Add("Key3", "Anirban");



Now in a button click, we will check if that key is already there or not, if it is there then we will increment the value of the key and insert it :-

protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtValue.Text.Trim() != "")
{
string strKey = "";
if (txtKey.Text.Trim() == "")
strKey = "Key" + (EmpHashTable.Keys.Count + 1);

if (!EmpHashTable.ContainsKey(strKey))
{
EmpHashTable.Add(strKey, txtValue.Text.Trim());

ListBoxCloths.DataSource = EmpHashTable;
ListBoxCloths.DataBind();
lblMessage.Text = "Hashtable Item Added";
}
else
{
lblMessage.Text = "Key Already Exist, Enter Another Key";
}

}
else
{
lblMessage.Text = "Please Enter an Item to Add";
}

}




Thanks and Regards
Akiii

Comments or Responses

Login to post response