Andrew_S
Andrew_S

Reputation: 23

Accessing a List within an ArrayList C#

I'm trying to access a List within an ArrayList to bind that list to a listbox.

Here is the code for my driver class.

public class Driver
{
    private string name;
    private string occupation;
    private DateTime dateOfBirth;
    private List<DateTime> dateOfClaim;

    public Driver(string name, string occupation, DateTime dateOfBirth, List<DateTime> dateOfClaim)
    {
        this.name = name;
        this.occupation = occupation;
        this.dateOfBirth = dateOfBirth;
        this.dateOfClaim = new List<DateTime>();
    }

    public string driverName
    {
        get{ return name; }
        set{ name = value; }
    }

    public string driverOccupation
    {
        get { return occupation; }
        set { occupation = value; }
    }

    public DateTime driverDateOfBirth
    {
        get { return dateOfBirth; }
        set { dateOfBirth = value; }
    }

    public List<DateTime> driverDateOfClaim
    {
        get { return dateOfClaim; }
        set { dateOfClaim = value; }
    }
}

I have a button which allows you to add a date for a claim to a driver, up to a maximum of 5 claims so I have a temporary list which holds the dates list before it is assigned to the list in the arraylist as the new driver has not yet been created in the arraylist.

Here are parts of the code from a form which declares and populates the arraylist.

private ArrayList drivers = new ArrayList();
private List<DateTime> claimDates = new List<DateTime>();

if (noOfClaims <= 4)
{
    claimDates.Add(dtpAddClaim.Value.Date);
    noOfClaims++;
}

if (noOfDrivers <= 4)
{
    drivers.Add(new Driver(txtName.Text, txtOccupation.Text, dtpDOB.Value.Date, claimDates));
    noOfDrivers++;
}

So my problem comes when trying to access the dateOfClaim list.

I'm trying to bind that list to a listbox and have tried using this to do that but am getting an error saying 'ArrayList' does not contain a definition for 'driverDateOfClaim'.

lbxClaimDates.DataSource = drivers.driverDateOfClaim;

Any help solving this would be greatly appreciated.

Upvotes: 0

Views: 137

Answers (1)

Lewis Taylor
Lewis Taylor

Reputation: 728

You need to index the array list. You would need to access an item of the array list and then acces driverDateOfClaim for a specific Driver instance in the ArrayList

lbxClaimDates.DataSource = ((Driver) drivers[0]).driverDateOfClaim 

Also in Drivers constructor you arent assigning the dateOfClaim parameter to the DateOfClaim property.

Upvotes: 1

Related Questions