2017-12-20 22 views
-1

私のWindowsフォームVB.netアプリケーションのすべてのコンボボックスをループしています。すべてのコンボボックス名を取得するVB.NET

私はこれが

Array.ForEach(Me.Controls.OfType(Of ComboBox).Items.Add(DataGridView1.Columns(i).Name))) 

を働くだろうが、私はそれを知っていないように思われる項目を参照することができないと想定していたが、私はすべてのリストを取得しようとしています

その時点でcomboboです私のコンボボックスの名前ので、私はうまくいけば、ループ内の名前のリストを使用してアイテムを追加し、選択したインデックスを読むことができますが、私の名前のリストは常に空白です。私は次のコードを使用して、messgboxにリストを送信して名前を取得しているかどうかを確認しようとしています。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click 
    Dim allComboBoxValues As String = "" 
    Dim c As Control 
    Dim childc As Control 
    For Each c In Me.Controls 
     For Each childc In c.Controls 
      If TypeOf childc Is ComboBox Then 
       allComboBoxValues &= CType(childc, ComboBox).Text & "," 
      End If 
     Next 
    Next 
    MsgBox(allComboBoxValues) 

    If allComboBoxValues <> "" Then 
     MsgBox(allComboBoxValues) 
    End If 
End Sub 
+0

あなたはただ、あなたはコンボ用の容器、パネルwhat's彼らのために毎回 – Plutonix

+0

を探して行くために持っていけないので、のCBOの配列を作成することができますグリッドビュー? – derloopkat

+0

あなたはコンテナの深さを複数持つことができるので、再帰せずにこの解決策は動作しないと思います。現在投稿されている回答は、私が思ったよりクリーンです。 – UnhandledExcepSean

答えて

1

蛇腹functionは、特定のタイプのすべての子Controlsを取得するために使用することができます。

Private Function GetAll(Control As Control, Type As Type) As IEnumerable(Of Control) 
     Dim Controls = Control.Controls.Cast(Of Control)() 
     Return Controls.SelectMany(Function(x) GetAll(x, Type)).Concat(Controls).Where(Function(y) y.GetType = Type) 
End Function 

使用法:あなたのニーズに

GetAll(Me, GetType(Combobox)) 

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click 
    Dim Values As String = String.Empty 
    For Each ComboBox As ComboBox In GetAll(Me, GetType(ComboBox)) 
     Values &= ComboBox.Text & "," 
    Next 
    MsgBox(Values) 
End Sub 

Function retrieved from this answer and converted to vb.net

+0

これは素晴らしい作品に感謝していただきありがとうございます! – Summers

0

私はこの拡張メソッドを使用します。それはかなりきれいなジェネリック薬を使用しています。コメントで述べたように、再帰が必要です。あなたのシナリオで

Public Module ExtensionMethods 

    <Extension()> 
    Public Function ChildControls(Of T As Control)(ByVal parent As Control) As IEnumerable(Of T) 
     Dim result As New List(Of T) 
     For Each ctrl As Control In parent.Controls 
      If TypeOf ctrl Is T Then result.Add(CType(ctrl, T)) 
      result.AddRange(ctrl.ChildControls(Of T)()) 
     Next 
     Return result 
    End Function 

End Module 

使用法:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click 
    Dim myCombos = Me.ChildControls(Of ComboBox) 
    Dim allComboBoxValues = String.Join(", ", myCombos.Select(Function(c) c.Text)) 
    If myCombos.Any() Then 
     MsgBox(allComboBoxValues) 
    End If 
End Sub 
+0

ありがとうございました!これを行うこの方法は、このアプリケーションの他の部分で役立ちます。 – Summers

関連する問題