将所有值添加到DataTable,而不仅仅是最后一个

本文关键字:不仅仅是 最后一个 DataTable 添加 | 更新日期: 2023-09-27 18:18:05

我有这个循环,但最后一个值被保存,我如何保存循环的所有值到datagridview

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++;
}

将所有值添加到DataTable,而不仅仅是最后一个

您需要设置您的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;