Search code examples
c#datagridviewemail-attachments

Adding Multiple attachments for a DataGridView with Button Click


I wrote this code for adding multiple attachments to the datagridview with button click, but i m able to add only one attachment at a time. it wont add multiple attachments with the next button click, please provide a solution,

thanks

this is the code i tried

       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;

Solution

  • Breakpoint at the last line (from comment): Well, of course this doesn't resolve the issue, but now you know the DataTable itself is wrong. Now proceed upwards your code with the breakpoint. You can set it on the DataTable dt = new DataTable(); line and look into the line above, when hovering above the ofdialog, look into it's collections of files in FileNames.

    enter image description here

    With OpenFileDialog1.Multiselect = True you should get number of files equal to what you selected in the OpenFileDialog.

    Next candidate is the filename array with breakpoint on foreach, checking number of items in this array.

    Here is code I am using for comparison:

    C# (converted):

    OpenFileDialogDXF.Title = "Choose your files";
    OpenFileDialogDXF.InitialDirectory = @"C:\users\XXXXX\Documents\";
    OpenFileDialogDXF.Filter = "DXF Files|*.dxf";
    OpenFileDialogDXF.Multiselect = true;
    
    if (OpenFileDialogDXF.ShowDialog() == DialogResult.OK)
    {
        for (var ir = 0; ir <= OpenFileDialogDXF.FileNames.Count - 1; ir++)
            LoadDXF(OpenFileDialogDXF.FileNames(ir));
    }
    

    VB.NET:

    Private Sub BtnOpenDxf_Click(sender As Object, e As EventArgs) Handles BtnOpenDxf.Click
        OpenFileDialogDXF.Title = "Choose your files"
        OpenFileDialogDXF.InitialDirectory = "C:\users\XXXXX\Documents\"
        OpenFileDialogDXF.Filter = "DXF Files|*.dxf"
        OpenFileDialogDXF.Multiselect = True
    
        If OpenFileDialogDXF.ShowDialog() = DialogResult.OK Then
            For ir = 0 To OpenFileDialogDXF.FileNames.Count - 1
                Call LoadDXF(OpenFileDialogDXF.FileNames(ir))
            Next
        End If
    

    Where LoadDXF is a my custom sub which handles each file.

    EDIT:

    Thinking about your code, if the OpenFileDialog gets multiple results, the place I'd look for a problem is this line:

    string[] filename = ofdialog.FileNames;
    

    It might need some conversion like .ToArray().