2017-03-17 45 views
0

我需要在表單中添加可變數量的ComboBoxes,之後我需要從ComboBoxes讀取輸入。在窗體中動態添加多個組合框並讀取添加的組合框的輸入?

我有這樣的代碼 -

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
     Dim n As Integer = Int(QsnNo.Text) 
     Dim i As Integer = 0 
     Do While i <= n 
      ComboGen(i) 
      i = i + 1 
     Loop 
    End Sub 

    Public Function ComboGen(ByVal n As Integer) 
     Dim newCombo As New ComboBox 
     With newCombo 
      .Name = "MyComboBox" & n.ToString 
      .Left = 10 
      .Top = 10 + (20 * n) + 20 
      .Width = 70 
      .Height = 20 
      .Items.Add("A") 
      .Items.Add("B") 
      .Visible = True 
     End With 
     Me.Controls.Add(newCombo) 
     Return 0 
    End Function 

而且我可以添加組合框。但是當我點擊Button2時,我想在稍後閱讀組合框的輸入。我不能。我怎樣才能做到這一點?

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles 

    Button2.Click 
      TextBox1.Text = MyComboBox1.selectedItem 
     End Sub 

我需要這樣的輸出。

回答

1

您可以將事件處理程序添加到您創建的每個組合框。這樣,您可以在運行時輕鬆使用所有組合框屬性。

完整的示例:

Public Class Form1 
    Dim intTop As Integer = 1 
    Dim strText As String 
    Dim cmb As ComboBox 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     AddNewTextBox() 
     AddHandler cmb.GotFocus, AddressOf cmb_Click 
    End Sub 

    Public Function AddNewTextBox() As ComboBox 
     cmb = New ComboBox 
     Me.Controls.Add(cmb) 
     cmb.Top = intTop * 25 
     cmb.Left = 10 
     cmb.Text = "ComboBox " & Me.intTop.ToString 
     intTop = intTop + 1 
     Return cmb 
    End Function 

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
     TextBox1.Text = strText 
    End Sub 

    Private Sub cmb_Click(sender As Object, e As EventArgs) 
     strText = sender.Text 
    End Sub 

End Class 
1

您可以通過它的名稱訪問控制:

MsgBox(Me.Controls("MyComboBox" & intYourComboBoxNumber).SelectedItem) 
1

你能做的就是聲明你的窗體類List(Of ComboBox);

Private ComboBoxes As New List(Of ComboBox) 

然後你可以做的是在創建時將動態創建的ComboBox添加到該列表中;

ComboBoxes.Add(newCombo) 

以後要在此呼籲,只要它沒有設置,你可以做,例如:

TextBox1.Text = ComboBoxes(0).SelectedItem ' Rather than 1, do 0 - zero-based index. 

也;注意:ComboGen應該是一個Sub - 不是Function因爲你總是返回0,從來沒有得到一個「正確」的結果 - 但是,如果成功了,False如果不是你可以封裝你的代碼在一個Try/Catch返回一個布爾值,True

Public Function ComboGen(ByVal n As Integer) As Boolean 
    Try ' Start of your Try/Catch block. 
     Dim newCombo As New ComboBox 
     With newCombo 
      .Name = "MyComboBox" & n.ToString 
      .Left = 10 
      .Top = 10 + (20 * n) + 20 
      .Width = 70 
      .Height = 20 
      .Items.Add("A") 
      .Items.Add("B") 
      .Visible = True 
     End With 
     ComboBoxes.Add(newCombo) ' Add your ComboBox to the list. 
     Me.Controls.Add(newCombo) 
     Return True 
    Catch ex As Exception ' Catch your exception. 
     Return False 
    End Try ' End the Try/Catch block. 
End Function