I am practising c# with a phonebook example using Hashtable.
I have a class which have 2 simple methods below, somehow if I use my form method to access the class, I won't be able to get a search result but if I call it within the class I am able to, I have added in a count to check if there's any item in the pPhonebook and it's always 0 when accessed outside outside, appreciate if someone can point out my mistake, does it have something to do with my Hashtable declaration? Thanks.
public class Phonebook { public Hashtable pPhoneBook = new Hashtable(); public void AddContactInfo(string perName, string perContact) { pPhoneBook.Add(perName, perContact); SearchContactInfo(perName); // This is okay } public void SearchContactInfo(string perName) { MessageBox.Show(pPhoneBook.Count.ToString()); if (pPhoneBook.ContainsKey(perName)) { string value = (string)pPhoneBook[perName]; MessageBox.Show(value); } else { MessageBox.Show("Not Found"); } } Form:
private void txtSearch_Click(object sender, EventArgs e) { if (textBox3.Text != "") { Phonebook pB = new Phonebook(); pB.SearchContactInfo(textBox3.Text); // Not Okay } else { MessageBox.Show("Please fill in the Name field"); } } private void txtAdd_Click(object sender, EventArgs e) { if (textBox1.Text != "" & textBox2.Text != "") { Phonebook pB = new Phonebook(); pB.AddContactInfo(textBox1.Text, textBox2.Text); textBox1.Text = ""; textBox2.Text = ""; } else { MessageBox.Show("Please fill in both Name and Contact field"); } }