C# datatable column datatype


I'm importing data from an excel sheet into a datatable and I'm having a problem/question about the datatypes. When I create the datatable, I add the columns and their datatypes. After this I import the data from excel and this works fine. When I check the datatype of the columns it says what I expect. However, when I try and pass a value to a function I get the message that I'm trying to pass an object type, instead of the datatype I set.

here's my code (it's a simplified dataset):

public void importData(string _file)
        DataTable dtTest = new DataTable();
        dtTest.Columns.Add("a", typeof(Int32));
        dtTest.Columns.Add("b", typeof(Int32));

        string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data       Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", _file);
        OleDbConnection conn = new OleDbConnection(connString);


        OleDbDataAdapter objAdapter = new OleDbDataAdapter();

        string sheetName = "Sheet1";
        string sql = "SELECT * FROM [" + sheetName + "$]";

        OleDbCommand objCmdSelect = new OleDbCommand(sql, conn);
        objAdapter.SelectCommand = objCmdSelect;



the function 'form.write()' accepts an integer.

when I check the datatype before I try and pass the value to form.write, it says it's Int32.

if (dtTest.Columns[0].DataType == typeof(Int32))
            //this is true

what am I doing wrong?

Best Solution

the function 'form.write()' accepts an integer.

Since form.Write accepts an integer, you need to cast it from object to int:

int a = dtTest.Rows[0].Field<int>("a");

Late binding is not allowed in C#, you must use the correct type at compile-time.