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);
Related
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);
}
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!
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.
}
I am trying to make an enroll/withdraw student into course project however I am not entirely sure how to add specific students to specific course.
I have a Course and Student class, and then a xaml window with a combobox, and list box with appropriate buttons.
When I press the enrol right now it simply takes the selected student and adds it into the "EnrolledStudents" text box to display the name however it doesn't actually assign it to the selected Course.
Code I have so far:
public MainWindow()
{
InitializeComponent();
Course bsc = new Course("BSc(Hons) Applied Computing");
Course hnd = new Course("Higher National Diploma (HND) Applied Computing");
Course partTime = new Course("Computer Science Part Time (MSc)");
Student andy = new Student("Andy", "Watt");
Student dave = new Student("Dave","Newbold");
Student daniel = new Student("Daniel","Brown");
lbCourses.Items.Add(bsc);
lbCourses.Items.Add(hnd);
lbCourses.Items.Add(partTime);
cbStudents.Items.Add(andy);
cbStudents.Items.Add(dave);
cbStudents.Items.Add(daniel);
}
and the enroll button click code:
private void butEnroleStudent_Click(object sender, RoutedEventArgs e)
{
cbStudents.SelectedItem.ToString();
lbEnroledStudents.Items.Add(cbStudents.SelectedItem);
}
but I am not sure where to go from here. My main issue is I don't know how to select the Student and Course instead of the string values.
As BradleyDotNET suggests, MVVM would be a lot easier for you to use, especially if your UI is going to get a lot more complicated. Also, any application like this is most likely going to rely on a database behind the scenes and hence you would be looking to bind all of your data controls.
That said, here is a sample that would achieve what you are trying to do there.
Presuming your Student class looks something like this:
private class Student
{
public String FirstName { get; set; }
public String Surname { get; set; }
public Student(String firstName, String surname)
{
FirstName = firstName;
Surname = surname;
}
public override string ToString()
{
return FirstName + " " + Surname;
}
}
And your Course class something like this:
private class Course
{
public String Name { get; set; }
public List<Student> EnrolledStudents { get; set; }
public Course(String name)
{
Name = name;
EnrolledStudents = new List<Student>();
}
public override string ToString()
{
return Name;
}
}
(Note that I have added a List to store the students enrolled on the given course)
Rather than adding to the Items property of your ListBox and ComboBox create collections that we can bind to:
private List<Student> _students;
private List<Course> _courses;
Constructing your test data then looks like this:
_courses = new List<Course>();
_courses.Add(new Course("BSc(Hons) Applied Computing"));
_courses.Add(new Course("Higher National Diploma (HND) Applied Computing"));
_courses.Add(new Course("Computer Science Part Time (MSc)"));
_students = new List<Student>();
_students.Add(new Student("Andy", "Watt"));
_students.Add(new Student("Dave", "Newbold"));
_students.Add(new Student("Daniel", "Brown"));
lbCourses.ItemsSource = _courses;
cbStudents.ItemsSource = _students;
Then when you click your enroll button
private void butEnroleStudent_Click(object sender, RoutedEventArgs e)
{
if (lbCourses.SelectedIndex >= 0 && cbStudents.SelectedIndex >= 0)
{
// Both a student and course are selected
Course selectedCourse = (Course)lbCourses.SelectedItem;
Student studentToAdd = (Student)cbStudents.SelectedItem;
if (!selectedCourse.EnrolledStudents.Contains(studentToAdd))
{
// Course does not already contain student, add them
selectedCourse.EnrolledStudents.Add(studentToAdd);
lbEnroledStudents.Items.Refresh();
}
}
}
Finally, to show the enrolled students in lbEnroledStudents as you click through the courses, you will need to hook up a new event handler in the xaml:
<ListBox x:Name="lbCourses" SelectionChanged="lbCourses_SelectionChanged"></ListBox>
And in the code behind:
private void lbCourses_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Course selectedCourse = (Course)lbCourses.SelectedItem;
lbEnroledStudents.ItemsSource = selectedCourse.EnrolledStudents;
}
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).