如何使用所有打开表单的列表填充列表框

时间:2013-06-30 04:13:49

标签: vb.net listbox

我有一个带有列表框的表单,我希望能够使用同一个应用程序的所有打开表单填充它。但是,我希望能够从列表框中选择一个项目,并能够关闭与列表框中该项目关联的表单。这可能吗?

2 个答案:

答案 0 :(得分:3)

我找到了问题的答案。以下代码有效:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
  Dim myForms As FormCollection = Application.OpenForms

  For Each frmName As Form In myForms
    ListBox1.Items.Add(frmName.Name.ToString)
  Next
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
  If Not ListBox1.SelectedIndex = -1 Then
    Dim myForm As Form = Application.OpenForms(ListBox1.Text)
    myForm.Close()
  End If
End Sub

ListBox1_SelectedIndexChanged下的代码可以很容易地放在按钮中。

答案 1 :(得分:1)

My.Application.OpenForms是项目中打开表单的集合。如下所示:

For Each f As Form In My.Application.OpenForms
    Me.SomeListBox.Items.Add(f)
Next

然后关闭所选项目,它是

DirectCast(Me.SomeListBox.SelectedItem, Form).Close()