devxlogo

Save a Round Trip to the Database

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 = NothingEnd Sub'At this point, you usually would use the SelectedValue property as the keyto do the'next lookup and pop the database for the corresponding row data, but withthis method,'you don't need to because you already have it - you just need to get it outPrivate Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal eAs 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 IfEnd Sub
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist