有人可以告诉我这里我做错了什么。我已经编译了我的代码,我让它读取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);
答案 0 :(得分:2)
你应该修改
int iRow = dataTable.Rows.Count;
到
int numFields = dbReader.FieldCount;
你的for循环然后变成
for (int i = 0; i < numFields; i++)
{
rowData += dbReader.GetValue(numFields).ToString();
}
答案 1 :(得分:0)
try with (Set dbReader.GetValue(0).ToString())
while (dbReader.Read())
{
for (int i = 0; i < iRow; i++)
{
rowData += dbReader.GetValue(0).ToString();
}
}