Search code examples
c#odbcarithmeticexception

Reading from ODBC reader - Arithmetic Overflow Exception


I am trying to retrieve data via an ODBC connection and put it in a datatable. The data coming in might have some cell values null.

Here is the code that I am using to import the data in a datatable:

DataTable dt = new DataTable();
OdbcCommand cmd = _conn.CreateCommand();
cmd.CommandText = sql;
OdbcDataReader reader = cmd.ExecuteReader();
bool firstRun = true;

while (reader.Read())
{
    object[] row = new object[reader.FieldCount];

    for (int i = 0; i < reader.FieldCount; i++)
    {
        if (firstRun)
            dt.Columns.Add(reader.GetString(i), reader[i].GetType());

        if (!reader.IsDBNull(i))
            row[i] = reader.GetValue(i);
    }
    firstRun = false;

    dt.Rows.Add(row);

On first row that I am reading I am creating the columns in the datatable. Then I continue reading the cell values for each row. Here's the catch: if i perform a select query returning a single column the operation above wworks. However if I perform it on multiple columns an exception gets thrown: Arithmetic operation resulted in an overflow on the line:if (firstRun) dt.Columns.Add(reader.GetString(i), reader[i].GetType());

What exactly am I missing here?

Thanks


Solution

  • reader.GetString(i) apparently returns the value of the specified column, NOT the name of the column. So I replaced it with a reader.GetName(i) to get the name of the column.