Hi.. do you think you can make an shortcut of this?
I have combobox like 40 combobox i have to put it like

combobox1.additem("sample")
combobox1.additem("sample2")
combobox1.additem("sample3")
combobox1.additem("sample4")

combobox2.additem("sample")
combobox2.additem("sample2")
combobox2.additem("sample3")
combobox2.additem("sample4")

combobox3.additem("sample")
combobox3.additem("sample2")
combobox3.additem("sample3")
combobox3.additem("sample4")   

until combobox40 i put it like that is there a way to make it easier?

Recommended Answers

All 2 Replies

try something like this:

For Each CB as Combobox in Me.Controls.ofType(Combobox)
    Select Case CB.Name.Length-7
        case1 ' Combobox1

        etc ....

Perhaps something like this:

   ' Since all your items are then same, create a list to use as a common DataSource for each ComboBox
   Dim items() As String = {"Sample 1", "Sample 2", "Sample 3", "Sample 4"}

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      'Since your ComboBoxes are named in a consecutive pattern, we can look up their names in a loop
      Dim cboName As String = String.Empty
      Dim p As Control
      For i As Int32 = 1 To 40
         cboName = "ComboBox" & i.ToString
         p = FindParent(Me, cboName)
         If p IsNot Nothing Then
            CType(p.Controls(cboName), ComboBox).DataSource = items
         End If
      Next
   End Sub


   ' Since the ComboBoxes may be parented in a child control, we need to identify their parent control
   ' a simple recursive search will do the trick
   Private Function FindParent(ByVal source As Control, ByVal name As String) As Control
      For Each c As Control In source.Controls
         If c.Name = name Then
            If c.Parent IsNot Nothing Then
               Return c.Parent
            Else
               Return source
            End If
         Else
            If c.HasChildren Then
               Dim parent As Control = FindParent(c, name)
               If parent IsNot Nothing Then Return parent
            End If 'c.HasChildren

         End If 'c.Name = name
      Next
      Return Nothing
   End Function
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.