【问题标题】:How to open multiselected files on Datagridview in C#如何在 C# 中的 Datagridview 上打开多选文件
【发布时间】:2020-03-17 03:02:27
【问题描述】:

我有很多 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】:

    如果我很好地理解了您的代码,那么您将遍历所有 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";
        }
    }
    

    【讨论】:

    • 谢谢你的回答,但还是同样的问题,datagridview 只显示最后一个文件被选中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    相关资源
    最近更新 更多