0

There I have bool that add files to ListBox:

If sp.ShowDialog() = DialogResult.OK Then
    For Each wp In sp.FileNames
        ListBox1.Items.Add(wp)
    Next wp
End If

and bool that add files to e-mail:

If ListBox1.Items.Count <> 0 Then
    For Each file In ListBox1.Items
        attch = New System.Net.Mail.Attachment(file)
        message.Attachments.Add(attch)
    Next file
End If

Is it possible to show only file names in ListBox but it will contains path to use it in second bool?

Because when I use sp.SafeFileNames it couldn't be sent because I don't have path.

Frank T
  • 8,268
  • 8
  • 50
  • 67
  • It very much sounds like you have 2 different questions there - one about FileOpenDialog and another about ListBox members. Please clarify – Ňɏssa Pøngjǣrdenlarp Oct 09 '17 at 16:09
  • @Plutonix i want on my ListBox only file names that can be sent as attachment. But when im using SafeFileNames variant it doesnt contains any path to be used in System.Net.Mail.Attachment() function. – Kamil Kiełczewski Oct 09 '17 at 16:16
  • Possible duplicate of [.NET Delete actual files from listbox](https://stackoverflow.com/questions/46503196/net-delete-actual-files-from-listbox) – Visual Vincent Oct 09 '17 at 16:21
  • Separating the view from the data is always best. Use a List(Of String) to store the path names, use Path.GetFileName() to generate the string you add to the ListBox. – Hans Passant Oct 09 '17 at 16:25
  • @HansPassant im so stupid, i cant handle it. Can you give me little example? – Kamil Kiełczewski Oct 09 '17 at 16:31

1 Answers1

0

You can use DisplayMember to present your items:

Imports System.IO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' add some selected files and show only their name in list

        Dim dialog As New OpenFileDialog

        If dialog.ShowDialog() <> DialogResult.OK Then Return

        Dim attachments = dialog.FileNames.Select(function(s) new Attachment(s)).ToArray()

        ListBox1.Items.AddRange(attachments)
        ListBox1.DisplayMember = "FileName"
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        ' do something with the attachments

        Dim attachments = ListBox1.Items.Cast (Of Attachment)

        For Each attachment In attachments
            Dim fullPath = attachment.FullPath
            Console.WriteLine(fullPath)
        Next
    End Sub
End Class

Public Class Attachment
    Public ReadOnly Property FileName As String
        Get
            Return Path.GetFileName(FullPath)
        End Get
    End Property

    Property FullPath As String

    Public Sub New(fullPath As String)
        Me.FullPath = fullPath
    End Sub
End Class
aybe
  • 15,516
  • 9
  • 57
  • 105