【问题标题】:DataTableReader.GetValue(int) is throwing ArguementOutOfRangeExceptionDataTableReader.GetValue(int) 正在抛出 ArguementOutOfRangeException
【发布时间】:2014-01-15 14:26:05
【问题描述】:

在我的代码的一部分中,我使用 DataTable 和 DataTableReader 从我的 SQLite 数据库中获取信息并将其添加到列表中。当程序到达 reader.GetValue 行时,程序会抛出 ArgumentOutOfRangeException。据我所知,没有理由发生这种情况。

    DataTable dt = db.GetDataTable(Program.CONN, "SELECT ID FROM table WHERE column LIKE 'False%'");
    using (DataTableReader dtr = dt.CreateDataReader())
    {
         while (dtr.Read())
         {
              int rt = 0;
              foreach (DataRow dr in dt.Rows)
              {
                   string line = dtr.GetValue(rt).ToString();//Arguement out of range exception being thrown here
                   idList.Add(line);
                   rt++;
              }
          }
     }

【问题讨论】:

    标签: c# sqlite exception datatable outofrangeexception


    【解决方案1】:

    您正在遍历行,而不是列。你应该这样做:

    DataTable dt = db.GetDataTable(Program.CONN, "SELECT ID FROM table WHERE column LIKE 'False%'");
    int count = dt.Columns.Count;
    using (DataTableReader dtr = dt.CreateDataReader())
    {
        while (dtr.Read())
        {
            for (int rt = 0 ; rt < count ; rt ++)
            {
                string line = dtr.GetValue(rt).ToString();
                idList.Add(line);
            }
         }
    }
    

    或者:

    DataTable dt = db.GetDataTable(Program.CONN, "SELECT ID FROM table WHERE column LIKE 'False%'");
    using (DataTableReader dtr = dt.CreateDataReader())
    {
        while (dtr.Read())
        {
            foreach (DataColumn col in dt.Columns)
            {
                string line = dtr[col.ColumnName].ToString();
                idList.Add(line);
            }
        }
    }
    

    【讨论】:

    • 并非如此。我遵循了他的语法,但最好使用 for 循环
    • @LarsTech 您确定 dtr[col.ColumnName] 可以与 DataTableReader 一起使用吗?
    • 我错过了列与行的事情。 A'aaack,很好的收获。赞成票。
    【解决方案2】:
    int fc = dataReader.FieldCount;
    while (dtr.Read())
    {
      for (int rt = 0 ; rt < fc ; rt ++)
      {
         if (fc > rt)
         {
             if (!(dtr.IsDBNull(rt)))
             {
                string line = dtr.GetValue(rt).ToString();
                idList.Add(line);
             }
          }
       }
    }
    

    【讨论】:

    • 我编辑了我的答案............我喜欢包含 if (!(dtr.IsDBNull(rt))) { ) 但那就是我。我的编辑也是因为 Plue 的“赶上”,所以这个答案应该得到认可。但是,我把这个答案留在这里....以防万一。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多