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