Question

In a section of my code I use a DataTable and a DataTableReader to get information from my SQLite database and add it to a list. When the program gets to the reader.GetValue line the program throws an ArgumentOutOfRangeException. As far as I've been able to tell there is no reason for this to be happening.

    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++;
              }
          }
     }
Was it helpful?

Solution

You are iterating through the rows, not the columns. You should do :

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);
        }
     }
}

Or :

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);
        }
    }
}

OTHER TIPS

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);
         }
      }
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top