vb.net 如何使用所有打开表单的列表填充列表框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17387080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate listbox with a list of all open forms
提问by TheRyan722
I have a form with a listbox, and I want to be able to populate it with all open forms of the same application. However, I want to be able to select an Item from the listbox, and be able to close the form associated with that item in the list box. Is this possible to do?
我有一个带有列表框的表单,我希望能够用同一应用程序的所有打开的表单填充它。但是,我希望能够从列表框中选择一个项目,并能够在列表框中关闭与该项目关联的表单。这有可能吗?
回答by TheRyan722
I found the answer to the issue. The following code works:
我找到了问题的答案。以下代码有效:
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
Where the code under ListBox1_SelectedIndexChangedcan very easily be placed in a button.
下面的代码ListBox1_SelectedIndexChanged可以很容易地放在一个按钮中。
回答by Ry-
My.Application.OpenFormsis a collection of the open forms in your project. So something like:
My.Application.OpenForms是项目中打开的表单的集合。所以像:
For Each f As Form In My.Application.OpenForms
Me.SomeListBox.Items.Add(f)
Next
Then to close the selected item, it's
然后关闭所选项目,它是
DirectCast(Me.SomeListBox.SelectedItem, Form).Close()

