Search code examples
c#.netms-accessoledboledbdatareader

IndexOutOfRangeException when reading in a field from an Access Database


I'm having trouble reading values into a list from an Access Database. The values look like this: Field is called EventDistance Values are 77 77 77 77 55 112 45 46

My code looks like this:

 private void StartSchedule_Click(object sender, EventArgs e)
    {
        string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\A2 Computing\C# Programming Project\TriHard.accdb";
        string SelectQuery = "SELECT Time.AthleteID, Athlete.AthleteName,
                              Time.EventTime, Event.EventDistance 
                              FROM Event INNER JOIN 
                                   (Athlete INNER JOIN [Time] 
                                    ON Athlete.[AthleteID] = Time[AthleteID]) 
                                    ON Event.[EventID] = Time.[EventID];";

        OleDbConnection Connection = new OleDbConnection(ConnectionString);
        OleDbCommand Command = new OleDbCommand(SelectQuery, Connection);
        Command.Connection.Open();
        OleDbDataReader Reader = Command.ExecuteReader(CommandBehavior.CloseConnection);

        PaceCalculator pace = new PaceCalculator();
        List<PaceCalculator> Distancelist = new List<PaceCalculator>();
        while (Reader.Read())
               {
                   pace.Distance = (int)Reader["Event.EventDistance"];
                   Distancelist.Add(pace);
               }

And its throwing IndexOutOfRanceException was unhandled for Event.EventDistance. There are only 8 integers to be read in, but there must be room for my data to expand. How do I make it so it just reads in the integers without throwing an index error?


Solution

  • When you run a query like

    SELECT Table1.Column1, Table2.Column2 FROM Table1 INNER JOIN Table2 ...
    

    the resulting columns in the OleDbDataReader are (usually) just named "Column1" and "Column2", so to reference them you just need to use

    reader["Column1"]
    

    not

    reader["Table1.Column1"]
    

    You are getting an IndexOutOfRange exception because there is no column in the reader named "Event.EventDistance".