简体   繁体   中英

How to dinamically change Combo box display member

I have a database in my VB program linked to a combo box. When selecting a name from combo box it will then auto fill the other text boxes with the related information. I'm now adding in a radio button to allow the switch of name & address within the combo box allowing the user to search depending on their preferences.

Does someone know a short line of code I could put within my radio button private sub which would change the display member of the combo box when selected?

Thanks

Below is example of how to switch display member . It is not necessarily makes design sense but it shows how to do it. This is working code BTW

Public Class Vendor
    Public Property Id As Integer
    Public Property Name As String
    Public Property Address As String    
End Class
 . . . . . 
' Form constructor
Dim listOfVendors As New List(Of Vendor)()
listOfVendors.Add(New Vendor() With {.Address = "A1", .Id = 1, .Name = "Name1"})
listOfVendors.Add(New Vendor() With {.Address = "A2", .Id = 2, .Name = "Name2"})
listOfVendors.Add(New Vendor() With {.Address = "A3", .Id = 3, .Name = "Name3"})

cboVendors.ValueMember = "Id" 
cboVendors.DisplayMember = "Name"
cboVendors.DataSource = listOfVendors 

. . . . .
' Assume SearchOptionChanged is handler for your radio buttons of the same group
Pivate Sub SearchOptionChanged(sender As Object, e As EventArgs) Handles rbSearchbyName.CheckedChanged, rbSearchbyAddress.CheckedChanged

    Dim rb As RadioButton = CType(sender, RadioButton)
    If rb.Name = "rbSearchbyName" AndAlso rb.Checked Then 
        cboVendors.DisplayMember = "Name"
    Else If rb.Name = "rbSearchbyAddress" AndAlso rb.Checked Then 
        cboVendors.DisplayMember = "Address"
    Else
        ' put your logic here
    End If

End Sub

' Getting item
Private Sub FillForm()
    ' Cool thing about this style is, now you can fill text boxes with data
    Dim v As Vendor = TryCast(cboVendors.SelectedItem, Vendor)
    If v Is Nothing Then
        MessageBox.Show("No Vendor selected")
    Else
        txtName.Text = v.Name
        txtAddress.Text = v.Address
        lblId.Text = v.Id
    End If

End Sub

This shows how to do it. You need to work out your logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM