如何通过Form Form从Form1访问Form2的实例? [英] How Do I Access An Instance Of Form2 From Form1 By his Form Text?

查看:147
本文介绍了如何通过Form Form从Form1访问Form2的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试通过他的form.text从Form1找到Form2的实例时遇到问题:



Form1的代码是:



I'm having problems trying to find an instance of Form2 by his form.text, from Form1:

Code of Form1 is:

Public Class Form1
    Dim nombform As String
    Public forma As Form2 = Nothing
   
    Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick

        Dim I As Integer
        For I = 0 To ListView1.SelectedItems.Count - 1
            nombform = (ListView1.SelectedItems(I).Text)
        Next
        forma = New Form2()
        forma.Text = nombform
        forma.Show()
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
      
    End Sub
End Class









Form2代码为:







Code of Form2 is:

Public Class Form2
    Inherits System.Windows.Forms.Form


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        For Each f As Form2 In Application.OpenForms
            If f.Text = "user1" Then
                MsgBox("Yes it is")
            End If
        Next
    End Sub
End Class









我得到的错误是:

无法将类型为InstanceTest.Form1的对象强制转换为InstanceTest.Form2


此行中的








The error i get is:
Unable to cast object of type InstanceTest.Form1 to type InstanceTest.Form2

in this line:

For Each f As Form2 In Application.OpenForms





我希望你们中的任何人都可以帮助我。



谢谢



I hope any of you can help me with this.

Thanks

推荐答案

那是有些奇怪代码!



Form2中的代码根本不需要查找Form2的实例 - 它已经是您正在寻找的实例!

当你遍历OpenForms集合时,它会返回所有表单 - 所以它首先从你的Form1实例开始,然后尝试将它强制转换为Form2 - 它不是一个(并且它不是从一)所以转换尝试失败,你得到错误信息。



如果你要做的是查看form2实例的Text属性,所有你必须做的是:

That's some odd code!

The code in Form2 shouldn't need to look for an instance of Form2 at all - it already is the instance you are looking for!
When you loop through the OpenForms collection, it returns all the forms - so it starts with your instance of Form1 first, and tries to cast that to a Form2 - it isn't one (and it isn't derived from one) so the cast attempt fails and you get the error message.

If what you are trying to do is look at the Text property of the form2 instance, all you have to do is:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    If Text = "user1" Then
        MsgBox("Yes it is")
    End If
End Sub

因为你在同一个班级内!

Because you are within the same class!


这篇关于如何通过Form Form从Form1访问Form2的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆