C# - How to use Dictionaries with GUI - c#

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.

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.
}

Related

How do I create new class objects when clicking a button?

I'll give you an example of what I want to see, but I can't do it in any way:
public class User
{
private string name;
private int age;
private int id;
public User(string name, int age, int id)
{
this.name = name;
this.age = age;
this.id = id;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string name = tb1.Text;
int age = Convert.ToInt32(tb2.Text);
int id = Convert.ToInt32(tb3.Text);
User ??? = new User(name,age,id);
}
??? - what should I put in the name? After all, I need to create a new object each time, respectively, with different names. How to do it?
You best create a list (List<User>) (or other type of collection) to which you can add new elements:
private readonly List<User> users = new List<User>();
private void Button_Click(object sender, RoutedEventArgs e)
{
string name = tb1.Text;
int age = Convert.ToInt32(tb2.Text);
int id = Convert.ToInt32(tb3.Text);
users.Add(new User(name,age,id));
}
This list could be defined the class containing Button_Click() or somewhere else depending on what needs to be done with the created User instances.
Access of the List elements:
To then get the third user creaded, use
user someUser = users[2];
To get the first John in the users list, use
user john = users.First(x => x.name != "John");
To get all Johns, use
List<user> johns = users.Where(x => x.name != "John");

New list updates original one

Here i am using this code for copy one list to another
public class Person
{
public string Name { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
var originalList = new List<Person>();
originalList.Add(new Person { Name = "name 1" });
originalList.Add(new Person { Name = "name 2" });
// var newList = originalList.ToList();
var newList = new List<Person>(originalList);
newList[0].Name = "New name";
Console.WriteLine(originalList[0].Name);
}
My result in console is 'New name', why this is happen? When i am updating my new list it also updates my original one. How can i fix this?
Do not worry, this is normal behavior, you have the original list, then you have another list filled in by the original, in your case, both lists point to the same items, which means that you have two references that point to the same memeory case , reason why you change an element from the original one the same element change in the second one and vice-versa .
Case 1 :
public class Person
{
public string Name { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
//here you have the original list, you create your list
//you add element to your list .
var originalList = new List<Person>();
originalList.Add(new Person { Name = "name 1" });
originalList.Add(new Person { Name = "name 2" });
// you create a second list , but here the contain the
// same element than the original list
var newList = new List<Person>(originalList);
newList[0].Name = "New name";
Console.WriteLine(originalList[0].Name);
}

How to Output from Generic Array List, to Listbox?

I am trying to output from Array list to a Listbox. My problem is I think is I do not know how to connect the Class to the Generic array list a made? The end result should look like this:
And the information should be then sorted like so: all the information enters the first list box, and then the above 18 goes to adults, and the below 18 to kids. My class looks like this:
namespace Patients
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public String Password { get; set; }
public Person() //Constructor
{
Age = 0;
Password = "";
}
public Person (string name, int age, string password) //Parameters
{
this.Name = name;
this.Age = age;
this.Password = password;
}
public override string ToString() //
{
return Name + Age.ToString() + Password; //outputs as a string
// return Name + " (" + Age + " years) " + Password ;
}
}
}
namespace Patients
{
public partial class WebForm1 : System.Web.UI.Page
{
public static void Page_Load(object sender, EventArgs e)
{
}
public void ButtonAdd_Click(object sender, EventArgs e)
{
Person p = new Person();
List<string> People = new List<string>();
People.Add(TextBoxName.Text);
People.Add(TextBoxAge.Text);
People.Add(TextBoxPassword.Text);
foreach (object Person in People)
{
ListBoxAll.Items.Add(p.Name + p.Age.ToString() + p.Password);
}
if (p.Age > 18)
{
ListBoxAdults.Items.Add(p.Name + p.Age.ToString() + p.Password);
}
else
{
ListBoxKids.Items.Add(p.Name + p.Age.ToString() + p.Password);
}
}
}
}
I think your problem is, that you don't set the Properties. In Fact you don't need a List at all, but you can use a List to keep hold of your patients. It's still not necessary though:
namespace Patients
{
public partial class WebForm1 : System.Web.UI.Page
{
// Define Property and initialize List
public List<Person> patients{ get; } = new List<Person>();
public static void Page_Load(object sender, EventArgs e)
{
}
public void ButtonAdd_Click(object sender, EventArgs e)
{
// Use the Constructor with Parameters
Person p = new Person(TextBoxName.Text, TextBoxAge.Text, TextBoxPassword.Text);
// Add your patient to your List
patients.Add(p);
// Use the ToString() of your Person
ListBoxAll.Items.Add(p.ToString());
if (p.Age > 18)
{
ListBoxAdults.Items.Add(p.ToString());
}
else
{
ListBoxKids.Items.Add(p.ToString());
}
}
}
}
Looks like you are mixing and matching a bit.
Try something like this.
Person p = new Person();
p.Name = TextBoxName.Text;
p.Age= TextBoxAge.Text;
p.Password= TextBoxPassword.Text;
ListBoxAll.Items.Add(p);
A few tricks that are nice to us, first off you can declare defaults for properties like so:
public string Name { get; set; } = "Steve";
public int Age { get; set; } = 1;
public String Password { get; set; } = "password";
However, it should also be noted that "" is the default for strings already and 0 is the default for non-nullable int, so you don't even need to worrying about those default values.
Declaring Age = 0; in the constructor is basically a waste of time in this case. (If it was a nullable int however the default is null)
Next up, since you are okay with defaults, you don't need to declare properties in the constructor like you are.
You can completely remove the constructor and just do the following:
var myPerson = new Person { Name = "Steve", Age = 18, Password = "Foo" };
Next up, you are losing all your existing people as soon as you exit the scope of the button click.
Instead you'll want to declare two lists of people outside the scope of the click method (that way they persist), something like "Adults" and "Children"
Then perhaps make a method called "PopulateLists" that would do the following:
Clear all list boxes
Add to each box the list of each groups names that apply (you can make an IQueryable by using Linq and Select statements on your list)
When you click the button, you should make a new person, assign it to the right list, then call PopulateLists()
Here's the info you need to get started:
Linq selection to get list of properties (in this case Im going to turn a List of People into a List of Ages, you can do the same with names though)
var ages = People.Select(p => p.Age);
The .Items property of a ListBox works the same as a list, it just visually shows itself. It's a list of strings specifically.
So for example you can do things like...
MyListBox.Items.Clear();
MyListBox.Items.Add(...);
MyListBox.Items.AddRange(...);
etc etc.
That should get you started!

How can I share variables between Web forms?

I am developing a web application on C# .Net and I need to pass variables from form to another form. For example, in the first form I have person class as following;
public class Person
{
private string _Name;
private string _Surname;
private string _DateOfBirth;
private string _Gender;
private string _Symptoms;
public Person()
{
Name = "Not available";
Surname = "Not available";
DateOfBirth = "Not available";
Gender = "Not available";
Symptoms = "Not available";
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string Surname
{
get { return _Surname; }
set { _Surname = value; }
}
public string DateOfBirth
{
get { return _DateOfBirth; }
set { _DateOfBirth = value; }
}
public string Gender
{
get { return _Gender; }
set { _Gender = value; }
}
public string Symptoms
{
get { return _Symptoms; }
set { _Symptoms = value; }
}
}
Then I assign values;
protected void Page_Load(object sender, EventArgs e)
{
Person MyPerson = new Person();
MyPerson.Name = txtName.Text;
MyPerson.Surname = txtSurname.Text;
MyPerson.DateOfBirth = txtBirth.Text;
MyPerson.Gender = listGender.Text;
MyPerson.Symptoms = checked(listSymptoms.Text);
}
So, how can I use these values into another form?
consider Another_form is a new form's class that contain a method should accept an object(person class)... for example
public void foo(Person obj)
{ ///your code }
that's it... then you have to pass variable from another form like
protected void Page_Load(object sender, EventArgs e)
{
Person MyPerson = new Person();
MyPerson.Name = txtName.Text;
MyPerson.Surname = txtSurname.Text;
MyPerson.DateOfBirth = txtBirth.Text;
MyPerson.Gender = listGender.Text;
MyPerson.Symptoms = checked(listSymptoms.Text);
another_form f=new another_form();
f.foo(MyPersion)
}
You could make your form produce a Person instance instead:
// within your form class, whatever it is
public Person CreatePerson()
{
Person MyPerson = new Person();
MyPerson.Name = txtName.Text;
MyPerson.Surname = txtSurname.Text;
MyPerson.DateOfBirth = txtBirth.Text;
MyPerson.Gender = listGender.Text;
MyPerson.Symptoms = checked(listSymptoms.Text);
return MyPerson;
}
Then, from anywhere in your code, call your form instance's CreatePerson method:
var personFromUI = yourFormInstance.CreatePerson();
That is one way to do it.
You could also expose the person as a property of your form, or pass a Person instance throughout your application objects, be it forms, controls, controllers, etc... while this goes beyond the scope of your question, this would be the preferred way because it keeps your UI code and your business code separated.
I'd advise that you look into separation of concerns. You may learn a trick or two there about proper application design.
Are you saying that you have populated a person object and then on another form you'd like to reference the same instance of that person object? Probably the simplest way would be to store the object in Session and then retrieve it on the second form.
protected void Page_Load(object sender, EventArgs e)
{
Person MyPerson = new Person();
MyPerson.Name = txtName.Text;
MyPerson.Surname = txtSurname.Text;
MyPerson.DateOfBirth = txtBirth.Text;
MyPerson.Gender = listGender.Text;
MyPerson.Symptoms = checked(listSymptoms.Text);
Session["CurrentPerson"] = MyPerson;
}
Personally, I don't normally use session this way and instead build that type of workflow into my apps persistence layer (e.g. Sql Server, Redis).

Copy List of objects into List in another object

I have been trying to figure this out in c#. I just started doing C# so I would appreciate your help.
I want to copy a list of Objects to a list in another object.
It looks something like this.
class Person
{
public String fName;
public String lName;
public List<House> housesOwned = new List<House>();
public Student(String FName, String LName)
{
this.fName = FName;
this.lName = LName;
}
}
class House
{
public String Address;
public House (String ad1){
this.Address1 = ad1;
}
}
Now, in my Form I created a list of objects type House (it has 2 objects of type House to be precise), which are the two houses that the person owns.
Something like : List<House> housesList = new List<House>;
Basically what I am trying to do is to copy the List<House> housesList created in the form to the List<House> housesOwned which is the list in the object Person. This will happen when pressing the submit button. So far I got this:
List<Person> person = new List<Person>(); // declared at the beginning of the form
.....
private void submit_Click(object sender, EventArgs e)
{
person.Add(new Person(personName.Text, personLName.Text));
//I do not know what comes next to copy the list housesList to the list housesOwned
MessageBox.Show("Done!");
}
I want the objects houses to be copied containing their addresses. Thank you very much for all your help.
Keep the instance of the new Person you created, then add the houseList to that instance.
private void submit_Click(object sender, EventArgs e)
{
var newPerson = new Person(personName.Text, personLName.Text);
newPerson.housesOwned.AddRange(houseList);
person.Add(newPerson);
MessageBox.Show("Done!");
}
Try this.
List<Person> people = new List<Person>();
var person = new Person(personName.Text, personLName.Text);
person.housesOwned.AddRange(housesList);
people.Add(person);

Categories