DataCombo - Proprieta Change




Dim strSQL As String = "Select Code,Description From MyTable"
Dim Connection As New OleDbConnection("PROVIDER=....")
Dim DA As New OleDbDataAdapter(strSQL, Connection)
Dim DS As New DataSet

DA.Fill(DS, "Codes")
Populate the ComboBox:
Dim dt As New DataTable = DS.Tables(0)
Dim dr As DataRow
'

' Populate the Combobox with the Descriptions.

'

For Each dr In dt.Rows()
cbo.Items.Add(dr("Description"))
Next
cbo.SelectedIndex = -1
To select a Description based on a "Code":
Dim intCBOIndex As Integer = -1

intCBOIndex = GetComboBoxIndexFromValue(cbo, dt, dr("Code"), 1)
cbo.SelectedIndex = intCBOIndex
Private Function GetComboBoxIndexFromValue( _
ByVal theCBO As ComboBox, _
ByVal theDataTable As DataTable, _
ByVal theValue As Object, _
ByVal theValueColumn As Integer) As Integer
'

' Return the index of the ComboBox item whose associated

' data value matches the passed in value. Data values ARE

' NOT stored in the Combox.

'

Try
'

' If the value to look for is blank, get out.

'

Dim strValue As String = theValue.ToString.Trim
If strValue = "" Then Return -1
'

' Data values are stored in a DataTable. Filter the datatable

' to find the row containing the value we are looking for.

'

Dim strDisplayValue As String
Dim strFilter As String

If theDataTable.Columns(theValueColumn).DataType _
Is System.Type.GetType("System.String") Then
strFilter = theDataTable.Columns(theValueColumn).ColumnName & "='" & strValue & "'"
Else
strFilter = theDataTable,Columns(theValueColumn).ColumnName & "=" & strValue
End If
theDataTable.DefaultView.RowFilter = strFilter
'

' Get the Display value from the datarow and find it in the ComboBox.

'

If theDataTable.DefaultView.Count = 0 Then
Return -1
Else
strDisplayValue = theDataTable.DefaultView(0)("DESCRIPTION").ToString()
theDataTable.DefaultView.RowFilter = ""
Return theCBO.FindStringExact(strDisplayValue)
End If

Catch ex As Exception
MessageBox.Show(....)
End Try

End Function











( datacomboproprietachange.html )- by Paolo Puglisi - Modifica del 17/12/2023