简体   繁体   English

索引超出范围异常 - C#

[英]Index out of range exception - C#

I wanted to read the data from SqlDatabase but I'm getting the IndexOutOfRangeException, here is the screenShot of my table: 我想从SqlDatabase读取数据但是我得到了IndexOutOfRangeException,这是我的表的screenShot: 在此输入图像描述

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(): 所以这里我有一个函数从数据库获取数据并将其存储到Lesson课程列表中,我在课程中得到了例外.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; }
}

IndexOutOfRangeException will be thrown by the SqlDataReader[string name] overload if the column name you provide does not exist. 如果您提供的列名不存在,则SqlDataReader[string name]重载将抛出IndexOutOfRangeException

You are including [] braces within your column name string eg "[num]" , the column name might be just "num" , try to remove the braces and you should be good. 您在列名称字符串中包含[]大括号,例如"[num]" ,列名可能只是"num" ,尝试删除大括号,您应该很好。

Try: 尝试:

lessons.Add(new Lesson(Day, (int)sdr["num"], 
(string)sdr["time"],(string)sdr["class"],(string)sdr["where"]));

Instead of calling the columns by their names, try calling them by their index 不要通过名称调用列,而是尝试通过索引调用它们

Something Like this 像这样的东西

while (sdr.Read()) { lessons.Add(new Lesson(Day, (int)sdr[1], (string)sdr[2],(string)sdr[3],(string)sdr[4])); while(sdr.Read()){lessons.Add(new Lesson(Day,(int)sdr [1],(string)sdr [2],(string)sdr [3],(string)sdr [4]) ); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM