Index out of range exception - C#

c#, sql

Solution

`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.

Problem

I wanted to read the data from SqlDatabase but I'm getting the IndexOutOfRangeException, here is the screenShot of my table: 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; } } ```

Original source