通过单击按钮为 DataGridView 添加多个附件

我编写了这段代码,用于通过单击按钮向 datagridview 添加多个附件,但我一次只能添加一个附件。单击下一个按钮不会添加多个附件,请提供解决方案,


谢谢


这是我尝试过的代码


       OpenFileDialog ofdialog = new OpenFileDialog();

        ofdialog.Multiselect = true;


        DataTable dt = new DataTable();

        dt.Columns.Add("Attachments");


        var res = ofdialog.ShowDialog();



           string[] filename = ofdialog.FileNames;

           string[] sfilename =  ofdialog.SafeFileNames;


           foreach (string fn in filename)

           {

               dt.Rows.Add(fn);

           }



            dataGridView1.DataSource = dt.DefaultView;

            dataGridView1.Columns["Attachments"].Width = 500;


慕森卡
浏览 93回答 1
1回答

收到一只叮咚

最后一行的断点(来自评论):当然,这不能解决问题,但现在您知道它本身DataTable是错误的。现在使用断点继续执行代码。您可以将其设置在线上DataTable dt = new DataTable();并查看上面的行,当将鼠标悬停在 上方时ofdialog,查看它的文件集合FileNames。OpenFileDialog1.Multiselect = True您应该获得的文件数量等于您在OpenFileDialog.下一个候选是filename带有断点的数组foreach,检查该数组中的项目数。这是我用来比较的代码:C#(转换后):OpenFileDialogDXF.Title = "Choose your files";OpenFileDialogDXF.InitialDirectory = @"C:\users\XXXXX\Documents\";OpenFileDialogDXF.Filter = "DXF Files|*.dxf";OpenFileDialogDXF.Multiselect = true;if (OpenFileDialogDXF.ShowDialog() == DialogResult.OK){&nbsp; &nbsp; for (var ir = 0; ir <= OpenFileDialogDXF.FileNames.Count - 1; ir++)&nbsp; &nbsp; &nbsp; &nbsp; LoadDXF(OpenFileDialogDXF.FileNames(ir));}VB.NET:Private Sub BtnOpenDxf_Click(sender As Object, e As EventArgs) Handles BtnOpenDxf.Click&nbsp; &nbsp; OpenFileDialogDXF.Title = "Choose your files"&nbsp; &nbsp; OpenFileDialogDXF.InitialDirectory = "C:\users\XXXXX\Documents\"&nbsp; &nbsp; OpenFileDialogDXF.Filter = "DXF Files|*.dxf"&nbsp; &nbsp; OpenFileDialogDXF.Multiselect = True&nbsp; &nbsp; If OpenFileDialogDXF.ShowDialog() = DialogResult.OK Then&nbsp; &nbsp; &nbsp; &nbsp; For ir = 0 To OpenFileDialogDXF.FileNames.Count - 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Call LoadDXF(OpenFileDialogDXF.FileNames(ir))&nbsp; &nbsp; &nbsp; &nbsp; Next&nbsp; &nbsp; End If我的自定义子程序在哪里LoadDXF处理每个文件。编辑:考虑一下您的代码,如果OpenFileDialog获得多个结果,我要查找问题的地方就是这一行:string[] filename = ofdialog.FileNames;它可能需要一些转换,例如.ToArray().
打开App,查看更多内容
随时随地看视频慕课网APP