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; }
}
Generally, list index out of range means means that you are providing an index for which a list element does not exist.
IndexOutOfRangeException as an exception type that should not be thrown intentionally from your own source code.
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.
Try:
lessons.Add(new Lesson(Day, (int)sdr["num"],
(string)sdr["time"],(string)sdr["class"],(string)sdr["where"]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With