user6353178 user6353178 - 1 month ago 8
C# Question

C# - How to use Dictionaries with GUI

I'm struggling to understand how a user can add a value to a dictionary with the use of a GUI.

I've managed to do this with the use of a list:

List<Person> clients = new List<Person>();


Person x = new Person();
x.Name = nameTextbox.text;
x.Address = addressTextbox.Text;
clients.Add(x);

public void AddClientButton_Click(object sender, EventArgs e)
{
Class Person{

public string Name{
get {return Name}
value { name = value;}

public string Address{
get {return Address}
value { name = Address;}
}

}


I've just typed this out as I'm not on my Windows machine (so forgive me so any mistakes), but none-the-less it works. However, I'm required to use a Dictionary due to the fact it has a Key & Value.

Everyone seems to add the data themselves and within a ConsoleApplication, I'm required to let the User add the data with the use of a GUI. I was wondering if the concept is similar with the use of a Dictionary or are they worlds apart?

Dictionary<string, string> clients = new Dictionary<string, string();


Person x = new Person();
x.Name = nameTextbox.text;
x.Address = addressTextbox.Text;
clients.Add(x);

public void AddClientButton_Click(object sender, EventArgs e)
{
Class Person{

public string Name{
get {return Name}
value { name = value;}

public string Address{
get {return Address}
value { name = Address;}
}

}


Could someone please point me in the right direction, possibly with the use of an example so I can grasp the concept.

Thank you.

Answer

Assuming the name of the person is unique

Dictionary<string, Person> clients = new  Dictionary<string, Person>();

 ....

public void AddClientButton_Click(object sender, EventArgs e)
{ 
        Person x = new Person();
        x.Name = nameTextbox.text;
        x.Address = addressTextbox.Text;
        clients.Add(x.Name, x); //Beware, if the name is not unique an exception will be thrown.

}
Comments