Click here to Skip to main content
15,887,822 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am playing around with List<> of objects. I was trying to create a list of dates within a list. Basically an object list can contain i.e 3 dates.

Im not sure how to do it.

Class called people:
C#
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public List<Dates> numberOfDates{ get; set; } = new List<Dates>();


Class called Dates:
C#
public DateTime date { get; set; }


What I have tried:

In my main form I have two event handlers. One is AddPerson second is AddDates Basically when you add dates I want it to save into the AddPerson button to added into the object (If that make sense).

C#
private void AddPerson(object sender, EventArgs e)
{
Person person = new Person();
person.Name = txtFirstName.Text;
person.Surname = txtSurname.Text;
person.Age = int.Parse(txtAge.Text);





 private void btnAddDates_Click_1(object sender, EventArgs e)
        {
People people = new People();
Dates dates= new Dates();

dates.date = dtpClaim.Value; //dtp is the date time picker                  people.numberOfDates.Add(dates);
        }


In short, once I add a date/dates in the addDates event, it will add it to the specific person in the addPerson event.
Posted
Updated 24-Mar-17 1:37am
v3
Comments
[no name] 24-Mar-17 7:35am    
Well your code doesn't do what you says it does, but what is your question?
F-ES Sitecore 24-Mar-17 7:45am    
Your classes are quite confusing and how they to relate to each other is also confusing, I think you probably need to re-work how you store things and what you call them. But to add the date to people you would do

people.numberOfDates.Add (new dates {date = dtpClaim.Value});

1 solution

You need to identify the appropriate person instance - and I have no idea how you are storing them, you don't show that: the Person instance is created anew each time you add a a date, so it can't be there.

But once you have the Person, it's easy:
C#
myPerson.numberOfDates.add(dates);


BTW: try to avoid naming things as plurals unless they are a collection: "Dates" is a single date storage object, so it should be "Date", and "People" should probably be "Person" - but you appear to have a class for that as well...which gets confusing!
 
Share this answer
 
Comments
Member 13081540 24-Mar-17 8:19am    
Hey, thanks for the reply, I forgot to add the piece of code that shows how to store the person in the addPerson event handler. So its that -
List<driver> ListOfPeople = new List<driver>();
ListOfPeople.Add(person);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900