Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index out of range exception - C#

Tags:

c#

sql

I wanted to read the data from SqlDatabase but I'm getting the IndexOutOfRangeException, here is the screenShot of my table: enter image description here

So here I have a function that gets the data from database and stores it into List of Lesson class, and i'm getting the exception in the lessons.Add():

 public List<Lesson> GetLessonsFromDay(string Day)
 {
    command.CommandText = "SELECT * FROM [Scadule] WHERE [day]='" + Day + "'";
    con.Open();

    SqlDataReader sdr = command.ExecuteReader();
    List<Lesson> lessons = new List<Lesson>();
    while (sdr.Read())
    {
        lessons.Add(new Lesson(Day, (int)sdr["[num]"], (string)sdr["[time]"],(string)sdr["[class]"],(string)sdr["[where]"]));
    }

    con.Close();
    return lessons;
 }

And here my lessonClass:

public class Lesson
{
public Lesson(string Day, int Num, string Time, string Class, string Where)
{
    this.Day = Day;
    this.Num = Num;
    this.Time = Time;
    this.Class = Class;
    this.Where = Where;
}

    public string Day { get; set; }
    public int Num { get; set; }
    public string Time { get; set; }
    public string Class { get; set; }
    public string Where { get; set; }
}
like image 653
C-sharper Avatar asked Jan 05 '14 16:01

C-sharper


People also ask

What is index out of range?

Generally, list index out of range means means that you are providing an index for which a list element does not exist.

Should you throw an IndexOutOfRangeException?

IndexOutOfRangeException as an exception type that should not be thrown intentionally from your own source code.


2 Answers

IndexOutOfRangeException will be thrown by the SqlDataReader[string name] overload if the column name you provide does not exist.

You are including [] braces within your column name string e.g. "[num]", the column name might be just "num", try to remove the braces and you should be good.

like image 158
MichaC Avatar answered Oct 28 '22 09:10

MichaC


Try:

lessons.Add(new Lesson(Day, (int)sdr["num"], 
(string)sdr["time"],(string)sdr["class"],(string)sdr["where"]));
like image 24
Lews Therin Avatar answered Oct 28 '22 10:10

Lews Therin