LuckyLuke82 LuckyLuke82 - 10 months ago 95 Question

binding textbox to combobox items

I have 2 columns in datatable and both are shown in dropdown-list of combobox (multiple-column drop-down list). Now I want to display one column in combobox, and other one in texbox (with databinding). Code works, but 1 problem - I want to have my combobox.selectedIndex -1 when form opens, and textbox empty. Combobox is not an issue, but Texbox can't be cleared of text. Here is my code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Dim SQL As String = "SELECT Name,Surname from MyTable"

Dim dtb As New DataTable()
dtb.Columns.Add("Name", System.Type.GetType("System.String"))
dtb.Columns.Add("Surname", System.Type.GetType("System.String"))

Using con As OracleConnection = New OracleConnection("Data Source=MyDB;User Id=Lucky;Password=MyPassword;")



Using dad As New OracleDataAdapter(SQL, con)

End Using

Combobox1.DataSource = dtb
Combobox1.DisplayMember = "Surname"
Combobox1.AutoCompleteMode = AutoCompleteMode.Suggest
Combobox1.AutoCompleteSource = AutoCompleteSource.ListItems

Catch ex As Exception
End Try

TextBox1.DataBindings.Add("Text", dtb, "Name")
Combobox1.SelectedIndex = -1

End Using

End Sub

This code is, as you see, in form's load event. I have tried with Textbox databinding in Combobox.SelectedIndexChanged event with If statement too, but It didn't work.

P.S.: My desired output is that when user selects some item from combobox, both column values are shown in texbox & combobox. Code as you see works that, but Textbox can't be empty like combobox on form's load.

Any suggestions ?


Your source data table has no record with blank data in it so your textbox is always bound to one of the records with data. I'd implement this using a simple event handler instead of data binding.

Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedItem Is Nothing Then
        TextBox1.Text = ""
        TextBox1.Text = CStr(CType(ComboBox1.SelectedItem, DataRowView)("Name"))
    End If
End Sub