我的表单中有一个哈希表。所以基本上我有2个按钮添加和删除。当我将信息放入文本框并添加它时,将其添加到哈希表中。但是当我点击删除它删除它时,当它没有值时,它会显示错误。 问题:我想要做的是,当我将信息放入 textBox1 (未添加到Hashtable中)时,它应该给出错误,否则如果已经添加了值,则应该删除它。
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);
}
}
例如:如果我在Hashtable中添加2并尝试删除3,它仍然会删除它只是因为textBox中有一些值。
答案 0 :(得分:1)
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");
}
}
我稍微更改了代码。你错过了一些重要的事情。就像检查HashTable中的密钥是否已经存在于您尝试添加它们时一样。如果尝试添加现有密钥,则会发生异常。我也改变了方法的名称,你错过了在哈希表中添加两个文本框。