Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: .NET
Expertise: Intermediate
Apr 6, 2004

Save a Round Trip to the Database

Save a round trip to the database when a keyed item is selected from any list type. This example uses a combobox, but any type of list control that accomodates databinding can work.

Public Sub LoadComboBox()
    'A custom object - use your own db access method to get a table
    Dim sb As New SqlBuilder
    With sb
         .ConnectString = WinAppConfig.ConnectString
         .ObjectName = "Publishers"
         'Get ALL the columns fields from the database table
         .SQL = "SELECT * FROM publishers "
    End With

    'Load the table to the control's datasource
    ComboBox1.DataSource = sb.GetDataSet.Tables("Publishers")

    'Set the display and value properties
    ComboBox1.DisplayMember = "pub_name"
    ComboBox1.ValueMember = "pub_id"

    'Set the databinding with the table and key value
    ComboBox1.DataBindings.Add("SelectedValue", sb.GetDataSet.Tables(0),
"pub_id")
    sb = Nothing

End Sub

'At this point, you usually would use the SelectedValue property as the key
to do the
'next lookup and pop the database for the corresponding row data, but with
this method,
'you don't need to because you already have it - you just need to get it out

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e
As System.EventArgs) _
Handles ComboBox1.SelectedIndexChanged

    'Protect the code from the load event firings
    If ComboBox1.DataBindings.Count > 0 Then
        Dim bmb As BindingManagerBase = Me.BindingContext(ComboBox1)
        Dim en As IEnumerator
        Dim dt As DataTable
        Dim dr As DataRow
        Dim str As String
        en = ComboBox1.DataBindings.GetEnumerator()
        en.MoveNext()
        dt = CType(ComboBox1.DataBindings.Item(0).DataSource, DataTable)
        dr = dt.Rows(ComboBox1.SelectedIndex)
        str = "You Selected: " & vbCr
        str &= "pub_id=" & dr.Item("pub_id") & vbCr
        str &= "pub_name=" & dr.Item("pub_name") & vbCr
        str &= "city=" & dr.Item("city") & vbCr
        str &= "state=" & dr.Item("state") & vbCr
        str &= "country=" & dr.Item("country") & vbCr
        MessageBox.Show(str)
    End If

End Sub
David Acree
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap