Question

Could someone please tell me what I am doing wrong here. I have compiled my code and I get it to read the ROWS and return the count. However, I get an error when saying the "Index was outside the bounds of the array" when I pass it to this line of code: rowData += dbReader.GetValue(iRow).ToString();

            //Create SQL strings
            string sql = "SELECT 'Computers' FROM [Sheet1$]";

            //Create the instances
            OleDbConnection dbConnection;
            OleDbDataAdapter dbAdapter;
            OleDbCommand dbCommand;
            OleDbDataReader dbReader;
            DataTable dataTable;

            //Call the instance
            dbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + @"\\slcnpr97\Desktop\Game Changers\\computers.xls" + "';Extended Properties='Excel 12.0 Xml;HDR=YES'");
            dbConnection.Open();
            dbAdapter = new OleDbDataAdapter(sql, dbConnection);
            dbCommand = new OleDbCommand(sql, dbConnection);
            dataTable = new DataTable();
            dbReader = dbCommand.ExecuteReader();
            dbAdapter.Fill(dataTable);

            //Method Variable
            int iRow = dataTable.Rows.Count;
            string rowData = null;

            while (dbReader.Read())
            {

                for (int i = 0; i < iRow; i++)
                {
                    rowData += dbReader.GetValue(iRow).ToString();
                }

            }
            //Close Connections 
            dbReader.Close();
            dbConnection.Close();
            MessageBox.Show(rowData);
Was it helpful?

Solution

try with (Set dbReader.GetValue(0).ToString())

while (dbReader.Read())
            {

                for (int i = 0; i < iRow; i++)
                {
                    rowData += dbReader.GetValue(0).ToString();
                }

            }

OTHER TIPS

You should modify

int iRow = dataTable.Rows.Count;

to

int numFields = dbReader.FieldCount;

Your for loop then becomes

for (int i = 0; i < numFields; i++)
{
    rowData += dbReader.GetValue(numFields).ToString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top