Results 1 to 18 of 18

Thread: Combobox and adding values manually

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2000
    Location
    San Diego - California
    Posts
    251

    Combobox and adding values manually

    How do you add the Valuemembers manually.

    I want to populate a combobox manually and not through databinding. With each Displaymember I add, I would like to add an associated reference value - like the itemdata value in VB6.

    Is there any simple method of doing this.

  2. #2
    Junior Member
    Join Date
    Oct 2002
    Posts
    31
    Microsoft has done away with the ItemData property and replaced it with ValueMember, which is completely useless unless you bind the combobox to a live datasource.

    This is a unique solution to the same problem alot of people are experiencing but have no answer for, other than binding to a data source.

    Seeing as the ComboBox.Tag property supports an Object, why not preload an array object with the primary key values and stick the whole thing in the combobox tag property? Works for me.

    ***** I hate Micro$oft some days...

    x--------- snip here -----------x

    'Declarations:

    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Data.OleDb
    Imports Microsoft.VisualBasic


    'Calling Convention:

    LoadComboBoxItems (cboExistCond, "ExistingCond", "Condition", "ExistingCond_ID", "")


    'Black-box sub that populates a combobox with records from a table:

    Private Sub LoadComboBoxItems( _
    ByVal cboComboBox As ComboBox, _
    ByVal strTableName As String, _
    ByVal strFieldName As String, _
    ByVal strUniqueKeyField As String, _
    ByVal strTableFilter As String _
    )


    Dim objConn As OleDbConnection
    Dim objAdap As OleDbDataAdapter
    Dim objDS As New DataSet()
    Dim sSQL As String
    Dim objTBL As DataTable
    Dim iCnt As Integer
    Dim strFieldContents As String

    Dim sConnect As String = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=c:\data\MyAccessDatabase.mdb"
    Dim strTargetDS As String = "DS_" & strTableName

    sSQL = "SELECT * FROM " & strTableName
    If strTableFilter <> Nothing Then
    sSQL = sSQL + " WHERE " & strTableFilter
    End If

    objConn = New OleDbConnection(sConnect)
    objAdap = New OleDbDataAdapter(sSQL, objConn)

    Try
    objAdap.Fill(objDS, strTargetDS)
    Catch eSql As Exception
    MsgBox(eSql.ToString)
    End Try

    Dim myIntArray(0) As Double

    For iCnt = 1 To objDS.Tables(strTargetDS).Rows.Count
    strFieldContents = objDS.Tables(strTargetDS).Rows(iCnt - 1).Item(strFieldName)
    ReDim Preserve myIntArray(iCnt)
    myIntArray(iCnt) = objDS.Tables(strTargetDS).Rows(iCnt - 1).Item(strUniqueKeyField)
    cboComboBox.Items.Add(strFieldContents)
    Next

    cboComboBox.Tag = myIntArray

    End Sub


    'The proof of the pudding...

    Private Sub cboExistCond_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboExistCond.SelectedIndexChanged

    MessageBox.Show("Selected Item Text: " & cboExistCond.SelectedItem & vbCrLf & _
    "Index: " & cboExistCond.SelectedIndex & vbCrLf & _
    "Primary Key: " & cboExistCond.Tag(cboExistCond.SelectedIndex + 1))

    End Sub

    x--------- snip here -----------x

    Best regards,
    George

  3. #3
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Actually you can use databinding with anything that implements IList or IListSource, even a class or collection class or things like an arraylist.

    VB Code:
    1. 'make data to fill list
    2.         Dim MyList As New ArrayList()
    3.         MyList.Add(New GenericList("Jack Hammer", 1))
    4.         MyList.Add(New GenericList("Sledge Hammer", 2))
    5.         MyList.Add(New GenericList("Screwdriver", 3))
    6.         MyList.Add(New GenericList("Wrench", 4))
    7.  
    8.         'bind list
    9.         ComboBox1.DataSource = MyList
    10.         ComboBox1.DisplayMember = "Display"
    11.         ComboBox1.ValueMember = "ID"
    12.  
    13. Public Class GenericList
    14.  
    15.     Private _Display As String
    16.     Private _ID As Integer
    17.  
    18.     Public Property Display() As String
    19.         Get
    20.             Return _Display
    21.         End Get
    22.         Set(ByVal Value As String)
    23.             _Display = Value
    24.         End Set
    25.     End Property
    26.  
    27.     Public Property ID() As Integer
    28.         Get
    29.             Return _ID
    30.         End Get
    31.         Set(ByVal Value As Integer)
    32.             _ID = Value
    33.         End Set
    34.     End Property
    35.  
    36.     Public Sub New()
    37.         MyBase.new()
    38.     End Sub
    39.  
    40.     Public Sub New(ByVal display As String, ByVal id As Integer)
    41.         Me.Display = display
    42.         Me.ID = id
    43.     End Sub
    44.  
    45. End Class

    Although you can store the whole object in the item so just reference that part of it that is the value from the SelectedItem property of the combo.

  4. #4
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Oh and one quick way to make a class bindable is just adding this:

    VB Code:
    1. Inplements System.ComponentModel.IListSource
    2.  
    3.     Private ReadOnly Property ContainsListCollection() As Boolean Implements IListSource.ContainsListCollection
    4.         Get
    5.             Return False
    6.         End Get
    7.     End Property
    8.  
    9.     Public Function GetList() As IList Implements IListSource.GetList
    10.         Dim al As New ArrayList()
    11.         al.Add(Me)
    12.         Return al
    13.     End Function

    There are also some other interfaces that inherit from IList or IListSource that you can use that provide more features like IBindingList.

  5. #5
    Junior Member
    Join Date
    Oct 2002
    Posts
    31
    I tried something similiar to that and couldn't get it to work, was getting some bs about not being able to bind ValueMember. Also was having problems properly declaring the public class. The main reason behind my post was to present a solution that was more intuitive for us VB6 folks. I also didn't want to rely on the VB6 compatibility library because who knows how long it will be supported.

    I'm still learning Object-oriented programming techniques and I am very new to this. Thanks for posting just the same. I'll try your method tomorrow.

    Cheers,
    George

  6. #6
    Junior Member
    Join Date
    Oct 2002
    Posts
    31
    Edneeis, I tried incoroprating your suggestion and can't figure out how to actually reference the values from the combobox (sigh).

    Could you please post a combobox_change event for your example? TIA

    P.S. Using your suggested method, it seems like one has to create a fair amount of code just to return something as simple as as reference to itemdata. But alas, I hate relying on a kludges to do something (which is why I'm working with .Net in the 1st place.)

    Cheers,
    George

  7. #7
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Sure no problem:
    VB Code:
    1. Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    2.         Dim gl As GenericList = CType(ComboBox1.SelectedItem, GenericList)
    3.         MsgBox(gl.Display, , gl.ID)
    4.     End Sub

  8. #8
    Junior Member
    Join Date
    Oct 2002
    Posts
    31
    Where were you two days ago??
    Thanks for the excellent example

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Nov 2000
    Location
    San Diego - California
    Posts
    251
    Ednis - Good job.

    I agree where were you 4 months ago.

  10. #10
    Hyperactive Member stingrae's Avatar
    Join Date
    Apr 2002
    Location
    Sydney
    Posts
    401

    Thumbs up

    Edneesis:

    you are a LEGEND!

    Microsoft: WHY make our lives so difficult?

    ??
    "The passion lives to keep your faith, though all are different, all are great" ... Michael Hutchence 1960-1997.

    Windows & Web Developer
    Specialising in Visual Basic .Net & Client Server Programming & Client/Customer Relations Databases
    Sutherland Shire, Sydney Australia
    www.stingrae.com.au
    Developer of Arnold - Gym & Martial Arts Database Management System
    www.gymdatabase.com.au

  11. #11
    Registered User
    Join Date
    Nov 2002
    Location
    Växjö, Sweden
    Posts
    314
    A thing worth mentioning in this thread is the fact that Comboboxes, Listboxes and other objects of the kind do accept objects as listitems. Therefore there is no need for the itemdata and such anymore. You just make your own Item class and its done.

    Code:
    Public Class ListItem
    
        Dim m_ItemData As String
        Dim m_ItemDisplay As String
    
        Sub New(ByVal Value As String, ByVal Data As String)
            Me.m_ItemData = Data
            Me.m_ItemDisplay = Value
        End Sub
    
        Overrides Function ToString() As String
            Return ItemDisplay
        End Function
    
        Property ItemData()
            Get
                Return m_ItemData
            End Get
            Set(ByVal Value)
                m_ItemData = Value
            End Set
        End Property
    
        Property ItemDisplay()
            Get
                Return m_ItemDisplay
            End Get
            Set(ByVal Value)
                m_ItemDisplay = Value
            End Set
        End Property
    
    End Class
    You are now able to add ListItems to the combobox instead. Something like this....

    Code:
    Combobox1.Items.Add(New ListItem("Test", "1"))
    And to get it back you Cast it back to a listitem again.....

    Code:
    DirectCast(cboDiscrepancy.SelectedItem, ListItem).ItemData

  12. #12
    Hyperactive Member stingrae's Avatar
    Join Date
    Apr 2002
    Location
    Sydney
    Posts
    401
    Edneeis,

    i implemented your example and it works really well the first time, but after use it the second time it doesn't.

    by that i mean:
    i fill it with data once, then
    clear the object - items.clear (i also tried setting DataSource = Nothing)
    then run the same function to fill the data.

    on the second and subsequent runs, all that appears in my listbox is "MyApplicationName.GenericList".

    are you able to help?

    cheers
    "The passion lives to keep your faith, though all are different, all are great" ... Michael Hutchence 1960-1997.

    Windows & Web Developer
    Specialising in Visual Basic .Net & Client Server Programming & Client/Customer Relations Databases
    Sutherland Shire, Sydney Australia
    www.stingrae.com.au
    Developer of Arnold - Gym & Martial Arts Database Management System
    www.gymdatabase.com.au

  13. #13
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    I'll check it out but off the top of my head, you may need to reset the DisplayMember. Did you try that?

  14. #14
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Well I so far haven't been able to reproduce the problem, everything worked fine for me. Can you post your code and I'll try and help.

  15. #15
    Hyperactive Member stingrae's Avatar
    Join Date
    Apr 2002
    Location
    Sydney
    Posts
    401
    Thanks for your quick reply. As mentioned, when i run it the first time, sweet, then the second call, it's a little bizarre?

    here are my functions:

    Code:
        Private Sub lstItemDescriptions_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstItemDescriptions.SelectedIndexChanged
            lstDates.DataSource = Nothing
            Dim gl As GenericList = CType(lstItemDescriptions.SelectedItem, GenericList)
            LoadItemDates(lstDates, gl.ID)
        End Sub
    
        Public Function LoadItemDates(ByVal objDates As Object, ByVal ItemID As Integer)
            Dim strSQLStm As String = "SELECT * " & _
                                      "FROM tbl_ItemDates " & _
                                      "WHERE itd_Item = " & ItemID & " " & _
                                      "ORDER BY itd_Start DESC"
            Dim cmdDates As New OleDb.OleDbCommand(strSQLStm, gconDatabase)
            Dim datDates As OleDb.OleDbDataReader
            Dim mylist As New ArrayList()
            Dim blnItemFound As Boolean = False
    
            cmdDates.Connection = gconDatabase
            datDates = cmdDates.ExecuteReader
            Do Until datDates.Read = False
                blnItemFound = True
                mylist.Add(New GenericList(Format(datDates("itd_Start"), "ddd dd-MM-yyyy"), datDates("itd_ID")))
            Loop
            datDates.Close()
            objDates.DataSource = mylist
            If blnItemFound = True Then objDates.ValueMember = "Display"
        End Function
    "The passion lives to keep your faith, though all are different, all are great" ... Michael Hutchence 1960-1997.

    Windows & Web Developer
    Specialising in Visual Basic .Net & Client Server Programming & Client/Customer Relations Databases
    Sutherland Shire, Sydney Australia
    www.stingrae.com.au
    Developer of Arnold - Gym & Martial Arts Database Management System
    www.gymdatabase.com.au

  16. #16
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Try this:
    VB Code:
    1. Private Sub lstItemDescriptions_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstItemDescriptions.SelectedIndexChanged
    2.         lstDates.DataSource = Nothing
    3.         Dim gl As GenericList = CType(lstItemDescriptions.SelectedItem, GenericList)
    4.         LoadItemDates(lstDates, gl.ID)
    5.     End Sub
    6.  
    7.     Public Function LoadItemDates(ByVal objDates As Object, ByVal ItemID As Integer)
    8.         Dim strSQLStm As String = "SELECT * " & _
    9.                                   "FROM tbl_ItemDates " & _
    10.                                   "WHERE itd_Item = " & ItemID & " " & _
    11.                                   "ORDER BY itd_Start DESC"
    12.         Dim cmdDates As New OleDb.OleDbCommand(strSQLStm, gconDatabase)
    13.         Dim datDates As OleDb.OleDbDataReader
    14.         Dim mylist As New ArrayList()
    15.         Dim blnItemFound As Boolean = False
    16.  
    17.         cmdDates.Connection = gconDatabase
    18.         datDates = cmdDates.ExecuteReader
    19.         Do Until datDates.Read = False
    20.             blnItemFound = True
    21.             mylist.Add(New GenericList(Format(datDates("itd_Start"), "ddd dd-MM-yyyy"), datDates("itd_ID")))
    22.         Loop
    23.         datDates.Close()
    24.         objDates.DataSource = mylist
    25.         [color=red][b]objDates.DisplayMember = "Display"
    26.         objDates.ValueMember = "ID"[/b][/color]
    27.     End Function

  17. #17
    Hyperactive Member stingrae's Avatar
    Join Date
    Apr 2002
    Location
    Sydney
    Posts
    401
    Athley,

    I've been using your method ever since, and it works fantastic! Just one query though. How do you step through each item in the combo box looking for the right ItemData? for example here's the VB6 version:
    Code:
        For i = 0 To cboData.ListCount - 1
            If cboData.ItemData(i) = ID Then
                cboData.ListIndex = i
                Exit For
            End If
        Next i
    thanks
    "The passion lives to keep your faith, though all are different, all are great" ... Michael Hutchence 1960-1997.

    Windows & Web Developer
    Specialising in Visual Basic .Net & Client Server Programming & Client/Customer Relations Databases
    Sutherland Shire, Sydney Australia
    www.stingrae.com.au
    Developer of Arnold - Gym & Martial Arts Database Management System
    www.gymdatabase.com.au

  18. #18
    Hyperactive Member stingrae's Avatar
    Join Date
    Apr 2002
    Location
    Sydney
    Posts
    401
    figured it out! here it is for anybody who needs it:

    Code:
        Public Function SearchCombo(ByVal FullCombo As ComboBox, ByVal ItemData As String)
            Dim i As Integer
            For i = 0 To FullCombo.Items.Count - 1
                If DirectCast(FullCombo.Items.Item(i), ListItem).ItemData = ItemData Then
                    FullCombo.SelectedItem = FullCombo.Items.Item(i)
                    Exit For
                End If
            Next i
        End Function
    "The passion lives to keep your faith, though all are different, all are great" ... Michael Hutchence 1960-1997.

    Windows & Web Developer
    Specialising in Visual Basic .Net & Client Server Programming & Client/Customer Relations Databases
    Sutherland Shire, Sydney Australia
    www.stingrae.com.au
    Developer of Arnold - Gym & Martial Arts Database Management System
    www.gymdatabase.com.au

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width