2017-03-17 81 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