Get ValueMember of Selected item in ListBox

前端 未结 1 902
既然无缘
既然无缘 2021-01-28 12:39

I\'ve seen a couple of posts asking a similar question but I have not been able to duplicate the answers in my code successfully. The following code adds items and their value m

相关标签:
1条回答
  • 2021-01-28 13:12

    ValueMember is supposed to indicate the property name of an object added to the Items collection: the property to use as the actual value for the items in the ListControl.

    You are not adding objects to the control, so Key from the hashtable is meaningless as the ValueMember. Your post references a file variable in passing, so I will assume this revolves around showing the filename while wanting to get the full pathname when selected/clicked. WebForms/Winforms/WPF was not indicated, I am assuming WinForms:

    Public Class myFile
       Public Property FileName As String
       Public Property FullPath  As String
    
       Public Property FileSize As Int64      ' just so there is something else
    
       Public Sub New(f as String, p as String, s as Int64)
           FileName = f
           FullPath = b
           FileSize = s
       End Sub
    
    End Class
    

    Lets say we want to add some of these to a ListBox, for each item added we want FileName to display as the text, but want to get them back by FullPath:

    Dim f As myFile
    ' assume these come from a fileinfo
    
    For Each fi as FileInfo in DirectoryInfo.GetFiles(searchFor)
        f = New myFile
        f.FileName = fi.Name
        f.FullPath = fi.FullPath
        f.FileSize = fi.Length
    
        ' myFile accepts all the prop values in the constructor
        ' so creating a new one could also be written as:
        ' f = New myFile(fi.Name, fi.FullPath, fi.Length)
    
        myListBox.Items.Add(f)
    Next n
    

    If the myFile objects were stored to a List(of myFile) rather than adding them to the control, we can bind the List as the DataSource and not have to iterate or copy:

    mylistBox.DataSource = myFileList
    

    Either way, Display- and ValueMember refer to the property names we wish to use:

    myListBox.DisplayMember = "FileName"    ' indicate property name of obj to SHOW
    myListBox.ValueMember = "FullPath"      ' prop name of object to return
    

    When you select a listbox item, myListBox.SelectedValue would refer to the FullPath of the myFile object clicked on. The SelectedIndex would still refer to the index of the item in the list.

    tl;dr

    ValueMember and DisplayMember refers to the Property Names of Objects represented in the list.

    Note:

    0 讨论(0)
提交回复
热议问题