2015-10-15 86 views
1

我有這個循環,但最後一個值被保存如何將循環的所有值保存到datagridview。將所有值添加到DataTable,而不僅僅是最後一個

int i = 0; 
while (i < pdfFiles.Length) 
{ 
    var firstPdfFilename = pdfFiles[i].FullName; 
    string ama = firstPdfFilename.ToString(); 
    Excel.Application application = new Excel.Application(); 
    Excel.Workbook workbookOne; 
    workbookOne = application.Workbooks.Open(ama); 
    Excel.Worksheet worksheet; 
    worksheet = workbookOne.Sheets[1]; 
    string test = worksheet.Cells[12, 3].Value.ToString(); 
    workbookOne.Close(true); 
    application.Quit(); 
    DataTable dt = new DataTable(); 
    dt.Columns.Add("My first column Name"); 
    dt.Columns.Add("My column Name"); 
    DataRow _ravi = dt.NewRow(); 
    _ravi["My first column Name"] = test; 
    _ravi["My column Name"] = test; 
    dt.Rows.Add(_ravi); 
    dataGridView1.DataSource = dt; 
    dataGridView1.AllowUserToAddRows = false; 
    i++; 
} 

回答

1

你需要設置你的DataTable並應用DataSource外循環:

int i = 0; 
DataTable dt = new DataTable(); 
dt.Columns.Add("My first column Name"); 
dt.Columns.Add("My column Name"); 
while (i < pdfFiles.Length) 
{ 
    var firstPdfFilename = pdfFiles[i].FullName; 
    string ama = firstPdfFilename.ToString(); 
    Excel.Application application = new Excel.Application(); 
    Excel.Workbook workbookOne; 
    workbookOne = application.Workbooks.Open(ama); 
    Excel.Worksheet worksheet; 
    worksheet = workbookOne.Sheets[1]; 
    string test = worksheet.Cells[12, 3].Value.ToString(); 
    workbookOne.Close(true); 
    application.Quit(); 
    DataRow _ravi = dt.NewRow(); 
    _ravi["My first column Name"] = test; 
    _ravi["My column Name"] = test; 
    dt.Rows.Add(_ravi); 
    i++; 
} 
dataGridView1.DataSource = dt; 
dataGridView1.AllowUserToAddRows = false; 
+0

Thavk你,你幫了不少忙! – user3142452

相關問題