如何在C#中打开Datagridview上的多选文件

问题描述 投票:1回答:1

我有很多excel文件,我想选择三个文件并在datagridview中显示它们,我尝试使用代码,但是我的代码仅显示最后一个,例如,我有1,2,3个文件,datagridview仅显示文件3。请问我该怎么办,

在此处输入代码

private void Button2_Click(object sender, EventArgs e)
{
  try
     {

       OpenFileDialog openFileDialog1 = new OpenFileDialog();
       openFileDialog1.Filter = "XML Files, Text Files, Excel Files| *.xlsx; *.xls; *.xml; *.txt; "; ;
       openFileDialog1.Multiselect = true;
       if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (String file in openFileDialog1.FileNames)
                {
                //tb_path is textbox
                tb_path.Text = file;
               // excelFilePath_com = tb_path.Text;
               }

           string constr = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + tb_path.Text + ";Extended Properties = \"Excel 12.0; HDR=Yes;\"; ");

                    OleDbConnection con = new OleDbConnection(constr);
                    con.Open();
                    drop_down_sheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);                
   //dro_down_sheet is combobox to choose which sheet to import 
                    drop_down_sheet.DisplayMember = "TABLE_NAME";
                    drop_down_sheet.ValueMember = "TABLE_NAME";


            }
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message,
         "Important Note",
         MessageBoxButtons.OK,
         MessageBoxIcon.Error,
         MessageBoxDefaultButton.Button1);
        }

    }
c# openfiledialog
1个回答
0
投票

如果我很了解您的代码,那么您正在遍历所有openFileDialog1.FileNames 之前对它们进行任何操作。如果将所有内容封装在foreach循环中,则应该能够使用所有选定的文件。例如:

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    foreach (String file in openFileDialog1.FileNames)
    {
        //tb_path is textbox
        tb_path.Text = file;
        // excelFilePath_com = tb_path.Text;
        string constr = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + tb_path.Text + ";Extended Properties = \"Excel 12.0; HDR=Yes;\"; ");

        OleDbConnection con = new OleDbConnection(constr);
        con.Open();
        drop_down_sheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        //dro_down_sheet is combobox to choose which sheet to import 
        drop_down_sheet.DisplayMember = "TABLE_NAME";
        drop_down_sheet.ValueMember = "TABLE_NAME";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.