Khắc phục lỗi: Parameter name: index

Mình dùng thư viện NPOI để xuất excel và code bên dưới nhưng bị lỗi ở text màu đỏ:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Mình mới mày mò về lập trình c# nên chưa hiểu, mong tất cả xem và giúp sửa lỗi. Cảm ơn !


InitializeWorkbook();
try
{


Sheet sheet = hssfworkbook.CreateSheet("NewSheet");


Row row;
Cell cell;
for (int i = 0; i <= dataGridView2.RowCount; i++)
{
row = sheet.CreateRow(i);
for (int j = 0; j <=dataGridView2.ColumnCount; j++)
{
cell = row.CreateCell(j);
sheet.GetRow(i).GetCell(j).SetCellValue(dataGridView2[j,i].Value.ToString());


}
}
WriteToFile();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
 

taplamhacker

♥ Thanh Trâm ♥
Mã:
[COLOR=#000000][FONT=Arial]for (int i = 0; i <= dataGridView2.RowCount; i++)[/FONT][/COLOR]
[COLOR=#000000][FONT=Arial]{[/FONT][/COLOR]
[COLOR=#000000][FONT=Arial]row = sheet.CreateRow(i);[/FONT][/COLOR]
[COLOR=#000000][FONT=Arial]for (int j = 0; j <=dataGridView2.ColumnCount; j++)[/FONT][/COLOR]
[COLOR=#000000][FONT=Arial]{[/FONT][/COLOR]
[COLOR=#000000][FONT=Arial]cell = row.CreateCell(j);[/FONT][/COLOR]
[COLOR=#000000][FONT=Arial]sheet.GetRow(i).GetCell(j).SetCellValue([/FONT][/COLOR][COLOR=#ff0000][FONT=Arial]dataGridView2[j,i].Value.ToString()[/FONT][/COLOR][COLOR=#000000][FONT=Arial]);[/FONT][/COLOR]
chỉ bé hơn không có bằng trong các vòng for, index vượt quá giới hạn
 
Mình chỉnh lại rồi nhưng lại báo lỗi không có giá trị nhỉ: Object reference not set to an instance of an object
Rõ ràng trong datagridview có dữ liệu rồi mà.

for (int i = 0; i <= dataGridView2.RowCount -1; i++)
{
row = sheet.CreateRow(i);
for (int j = 0; j < dataGridView2.ColumnCount; j++)
{
cell = row.CreateCell(j);
sheet.GetRow(i).GetCell(j).SetCellValue(dataGridView2[j,i].Value.ToString()); // Tại dòng này


}
}
 

snowolf901

Tuyết Lang
Mình chỉnh lại rồi nhưng lại báo lỗi không có giá trị nhỉ: Object reference not set to an instance of an object
Rõ ràng trong datagridview có dữ liệu rồi mà.

for (int i = 0; i <= dataGridView2.RowCount -1; i++)
{
row = sheet.CreateRow(i);
for (int j = 0; j < dataGridView2.ColumnCount; j++)
{
cell = row.CreateCell(j);
sheet.GetRow(i).GetCell(j).SetCellValue(dataGridView2[j,i].Value.ToString()); // Tại dòng này


}
}
dataGridVi ew2[j,i] thằng này null
 

taplamhacker

♥ Thanh Trâm ♥
Mình chỉnh lại rồi nhưng lại báo lỗi không có giá trị nhỉ: Object reference not set to an instance of an object
Rõ ràng trong datagridview có dữ liệu rồi mà.

for (int i = 0; i <= dataGridView2.RowCount -1; i++)
{
row = sheet.CreateRow(i);
for (int j = 0; j < dataGridView2.ColumnCount; j++)
{
cell = row.CreateCell(j);
sheet.GetRow(i).GetCell(j).SetCellValue(dataGridView2[j,i].Value.ToString()); // Tại dòng này


}
}
ở trên mình có ghi trong các vòng for, bạn chỉ sửa for dưới, sao k thử sửa luôn cái for ở trên nhỉ :thatbatngo:
 
Top