0
votes

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

        conn.Open();

        OleDbDataAdapter objAdapter = new OleDbDataAdapter();

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

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

        objAdapter.Fill(dtTest);
        conn.Close();

        form.write(dtTest.Rows[0]["a"]);
    }

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?

2

2 Answers

0
votes

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");
form.write(a);

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

0
votes

If I am understanding your post correctly, you may need to cast the value.

form.write(dtTest.Rows[0]["a"]);

I believe it should be:

form.write(Convert.ToInt32(dtTest.Rows[0]["a"]));

Without the Convert.ToInt32() you are referencing an object type.