Reputation: 171
I have a hashtable in my forms. So basically I have 2 button Add and Delete. When I put info in the textbox and add it adds it in the hashtable. But when I click delete it deletes it and when there's no value in it, it shows an error. Question: So what I want to do is that when I put info in textBox1 which is not added in the Hashtable, it should give an error otherwise if the value is already added, it should just delete it.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "" && b == "" || a == "" || b == "")
{
MessageBox.Show("Missing Input!");
}
else
{
MessageBox.Show("Added successfully");
label4.Text = a + " " + b;
}
}
private void button4_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(a)) // but this deletes it even if the value has not been added
{
MessageBox.Show(textBox1.Text + "has been removed");
Info.Remove(a);
}
}
For example: If I add 2 in Hashtable and try to delete 3, it will still delete it just because there's some value in the textBox.
Upvotes: 0
Views: 53
Reputation: 18127
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void AddToHashTable_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "" || b == "")
{
MessageBox.Show("Missing Input!");
}
else if(Info.ContainsKey(a) || Info.ContainsKey(b))
{
MessageBox.Show("Hash table already contain this key");
}
else
{
Info.Add(a);
Info.Add(b);
MessageBox.Show("Added successfully");
label4.Text = a + " " + b;
}
}
private void DeleteFromHashTable_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(a)) // but this deletes it even if the value has not been added
{
MessageBox.Show(a + " has been removed");
Info.Remove(a);
}
else
{
MessageBox.Show(a + " is not part of the hash table");
}
//same check here for b
if (b == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(b)) // but this deletes it even if the value has not been added
{
MessageBox.Show(b + " has been removed");
Info.Remove(b);
}
else
{
MessageBox.Show(b + " is not part of the hash table");
}
}
I change the code a little bit. You miss some crucial things. Like check if the keys are already exist in the HashTable when you try to add them. If you try to add existing key exception will occur. Also I changed name of the methods, you miss to add the both text boxes in the hash table.
Upvotes: 1