0

有人可以告诉我我在这里做错了什么。我已经编译了我的代码,我让它读取 ROWS 并返回计数。但是,当我将它传递给这行代码时,当我说“索引超出数组的范围”时出现错误: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);
4

2 回答 2

2

你应该修改

int iRow = dataTable.Rows.Count;

int numFields = dbReader.FieldCount;

你的 for 循环然后变成

for (int i = 0; i < numFields; i++)
{
    rowData += dbReader.GetValue(numFields).ToString();
}
于 2012-06-22T21:53:18.520 回答
0
try with (Set dbReader.GetValue(0).ToString())

while (dbReader.Read())
            {

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

            }
于 2012-06-22T21:48:19.043 回答