【问题标题】:list of controls for each form每个表单的控件列表
【发布时间】:2015-12-08 00:39:02
【问题描述】:

iam 使用 vb.net 2008,我有 2 个列表框,一个用于列出我的项目中的所有表单名称并且工作正常,但我需要的是当我单击表单列表时,另一个列表框应该向我显示所有listbox1 中所选表单名称中的控件!我一直在努力,但没有运气。请帮忙。这是列出所有表单的代码

Dim myAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
        Dim types As Type() = myAssembly.GetTypes()
        For Each myType As Object In types

            If myType.BaseType.FullName.ToString.ToUpper = "SYSTEM.WINDOWS.FORMS.FORM" Then
                ListBox1.Items.Add(myType.Name)
            End If
        Next

这就是我在 list2 中所尝试的

 Dim f As New Form
        f.Name = ListBox1.SelectedItem.ToString
        For Each c As Control In f.Controls
            ListBox2.Items.Add(c.Name)
        Next

【问题讨论】:

  • 这很狡猾:If myType.BaseType.FullName.ToString.ToUpper = "SYSTEM.WINDOWS.FORMS.FORM" Then。最好使用这个:If myType.BaseType Is GetType(Form) Then。使用Strings 来处理文本以外的事情应该永远是你最后的手段。
  • 另外,这将排除从 Form 以外的其他类型派生的表单。最好还是用这个:If GetType(Form).IsAssignableFrom(myType) Then.
  • 至于问题,创建Form 类的实例并更改其Name 并不会神奇地使其成为不同的类型。您必须首先实际创建该类型的实例。
  • Dim ddb As String = ListBox1.SelectedItem Dim x As String = System.Reflection.Assembly.GetExecutingAssembly.GetName.Name() Dim ProjAndForm As String = x + "." + ddb Dim objType As Type = Type.[GetType](ProjAndForm) Dim objForm As Control = DirectCast(Activator.CreateInstance(objType), Control)
  • Dim f As New Form 应该创建一个通用空白表单的实例,而不是您想要轮询的任何表单

标签: vb.net forms listbox controls


【解决方案1】:

好的!经过几个小时的狩猎 - 我希望这适用于 vb2008。它适用于vb2015,但让我们希望!获取所有表单列表的代码来自另一个来源。我在寻找答案时遇到的问题总是导致运行时转换出错——但最终这似乎奏效了。希望它也适用于您。

Public Class Form1
    Dim allforms() As Form
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        allforms = (From t As Type In Me.GetType().Assembly.GetTypes()
                    Where t.BaseType Is GetType(Form)
                    Let f = DirectCast(Activator.CreateInstance(t), Form)
                    Select f).ToArray
        For Each frm As Form In allForms
            ListBox1.Items.Add(frm.Name)
        Next
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        For Each c As Control In allforms(ListBox1.SelectedIndex).Controls
            ListBox2.Items.Add(c.Name)
        Next
    End Sub
End Class

【讨论】:

  • 您可能需要添加 Imports System.Linq
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多