I have a combobox which is filled with items from a table like this:

For Each rad In interntabell.Rows
                firstname = rad("firstname")
                lastname = rad("lastname")
                id = rad("id")
                ComboBox1.Items.Add(id & " " & firstname & " " & lastname)
            Next rad

What Im trying to do is to when I choose one name from the dropdown list the firstname shall go to one textbox1 and lastname go to textbox2. One way doing this may be to use the ID column wich is the the Primary Key. And do a new search in a button with that ID which fills the textboxes. But how can I get just a portion of the selected string in the combobox to a string so I can do a search on it. Desperate for help now, have been searching all over, but cant find anything helpful. Please help me.

Arild

Dani AI

Generated

Better than chopping the displayed string: keep structured data in the ComboBox so you never have to parse names out of a single concatenated string. Good points from and — splitting works for simple cases and corrected his snippet — but splitting by space is brittle (compound last names, middle names, prefixes, etc.). Put an object with ID/FirstName/LastName into the ComboBox.Items (or bind a typed list) and read properties directly.

Public Class Manager
  Public Property ID As Integer
  Public Property FirstName As String
  Public Property LastName As String

  Public Sub New(id As Integer, f As String, l As String)
    ID = id : FirstName = f : LastName = l
  End Sub

  Public Overrides Function ToString() As String
    Return FirstName & " " & LastName
  End Function
End Class

' Populate:
ComboBox1.Items.Add(New Manager(idValue, firstNameValue, lastNameValue))

' Read selection:
Dim m As Manager = TryCast(ComboBox1.SelectedItem, Manager)
If m IsNot Nothing Then
  TextBox1.Text = m.FirstName
  TextBox2.Text = m.LastName
  ' m.ID is available for DB lookups
End If

Notes and troubleshooting:

  • Check for Nothing before casting.
  • When filling the ComboBox, disable selection handling (use a simple loading flag) to avoid premature events.
  • For large lists use BeginUpdate/EndUpdate and clear Items before repopulating.
  • If you are data-binding, cast SelectedItem to a DataRowView (or use the bound object) to read fields directly instead of parsing Text.
  • If parsing must be used, pick a delimiter that cannot appear in names (for example '|') and limit the number of splits.

This keeps the UI robust and preserves the ID for any follow-up queries without fragile string manipulation — a cleaner, safer solution for .

Recommended Answers

All 5 Replies

You can use the Split method of String:

Read this http://www.dotnetperls.com/split-vbnet

'You will need a String Array to hold the names
'

Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
    If ComboBox1.SelectedIndex <> -1 Then
      Dim names() As String = ComboBox1.SelectedItem.ToString.Split(New Char() {" "c})
      TextBox1.Text = names(0)
      TextBox2.Text = names(1)
    End If
    
  End Sub

You can also bind the ComboBox to a DataTable and search the DataTable by the ComboBox selection.
http://www.java2s.com/Code/VB/Database-ADO.net/DatabaseDataBindingComboBox.htm

simpliest way:

Dim data As String() = comboBox1.SelectedItem.ToString()
textBox1.Text = data(0)
textBox2.Text = data(1)

Mitja Bonca, what exactly is the code you posted supposed to do other than error?

bukk123, see if this helps as well.

With ComboBox1
            If Not .SelectedIndex = -1 Then '// if item selected, since -1 ='s No item selected.
                With .SelectedItem.ToString.Split(" "c) '// .Split by " " and...
                    TextBox1.Text = .GetValue(0).ToString  '// get the first value.
                    TextBox2.Text = .GetValue(1).ToString '// get the second value.
                End With
            End If
        End With

Yes, you were right codeorder, I should do it like:

Dim data As String() = comboBox1.SelectedItem.ToString().Split(" "C)
textBox1.Text = data(0)
textBox2.Text = data(1)
Imports System.Data.OleDb

Public Class Form1

  Dim dt As New DataTable("Managers")

  Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
                                  "C:\Documents and Settings\DATA\managers.mdb")

  Dim managerId As Integer 'DB Table Primary Key

  'Keep ComboBox SelecteIndexChanged from doing anything until it is finished loading
  Dim loaded As Boolean = False

  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Call LoadManagersComboBox()
  End Sub
  Private Sub LoadManagersComboBox()

    'Managers.ID is the Primary Key. 
    'The 4th selected Item [MANAGER]is a concatanation 
    'of the first 3 to use in the ComboBox display.
    ' This way you won't have to waste time looping to fill your ComboBox.
    Dim sql As String = "SELECT Managers.ID, Managers.First_Name, Managers.Last_Name, " & _
                        "[Managers].[ID] & ' ' &  [Managers].[First_Name] & ' ' &  " & _
                        "[Managers].[Last_Name] AS [MANAGER] FROM Managers;"

    Dim cmd As New OleDbCommand(sql, conn)
    Dim da As New OleDbDataAdapter(cmd)


    Try
      da.Fill(dt)
    Catch ex As Exception
      MsgBox(ex.ToString)
    End Try

    With cmboUsers
      .DataSource = dt
      .DisplayMember = "MANAGER"
      .ValueMember = "ID"
      .SelectedIndex = -1
      loaded = True
    End With

  End Sub



  Private Sub cmboUsers_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmboUsers.SelectedValueChanged
    If loaded Then
      Dim arrManager() As String = cmboUsers.Text.Split(New Char() {" "c})

      'Set The userId variable for the searches
      managerId = CInt(cmboUsers.SelectedValue)

      'Load TextBoxes
      txtFirstName.Text = arrManager(1)
      txtLastName.Text = arrManager(2)
      txtID.Text = CStr(managerId)

    End If
  End Sub

  Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
    'Do Search of DataTable "dt" Stuff here
  End Sub
End Class
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.