Problem accessing class method
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 decl开发者_开发问答aration? 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");
}
}
This is because , you are creating 2 different Phonebook instances
In the search click, it appears that you are creating a new instance of teh phone book each time. So it is created new and empty. Nothing you added to it is retained. You should look in to making sure its always searching a single instance of your PhoneBook from your form.
I think it's because your phone book is empty, you have no people in it, so it returns no results.
You are getting 0 because your hash table is empty. You should call AddContactInfo method first, and than SearchContactInfo.
精彩评论