如何将表单、对象或数据传递给第二个表单 [英] How to pass a form, object or data to a second form

查看:49
本文介绍了如何将表单、对象或数据传递给第二个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了 2 个表单.第一个是您要备份的按钮.在第二个中有可以修改的路径.如何参考在按下备份"按钮后将获得 2 个表单的路径.当我关闭 form2 时保存了路径我知道如何用一种形式来做,但不幸的是我不能参考另一种形式.

I have created 2 forms. The first one is the button that you want to back up. In the second there are paths that can be modified. How to make a reference that after pressing the "backup" button will get a path of 2 forms. The path is saved when I closed form2 I know how to do it in one form but unfortunately I can not refer to another form.

表格 2 的来源:

Private Sub Browser_from1_Click(sender As Object, e As EventArgs) Handles Browser_from1.Click
        Dim FolderBrowserDialog1 As New FolderBrowserDialog
        FolderBrowserDialog1.ShowDialog()
        TextBox1from.Text = FolderBrowserDialog1.SelectedPath

        If Browser_from1.Text <> "" And TextBox1from.Text <> "" Then
            Backup.StartCopy.Enabled = True

        End If

    End Sub

    Private Sub Browser_to1_Click(sender As Object, e As EventArgs) Handles Browser_to1.Click
        Dim FolderBrowserDialog1 As New FolderBrowserDialog
        FolderBrowserDialog1.ShowDialog()
        TextBox2to.Text = FolderBrowserDialog1.SelectedPath

        If Browser_to1.Text <> "" And TextBox2to.Text <> "" Then
            Backup.StartCopy.Enabled = True

        End If
    End Sub

    Private Sub TextBox1from_TextChanged(sender As Object, e As EventArgs) Handles TextBox1from.TextChanged

    End Sub

    Private Sub save_settings_Click(sender As Object, e As EventArgs) Handles save_settings.Click
        My.Settings.pathmem = TextBox2to.Text
        My.Settings.pathmem1 = TextBox1from.Text
        My.Settings.Save()
    End Sub

    Private Sub setting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TextBox1from.Text = My.Settings.pathmem1
        TextBox2to.Text = My.Settings.pathmem
    End Sub
End Class

推荐答案

您不想创建对表单的引用 - 这将(或可能)创建一个全新的表单.您想保留表单引用.

You dont want to create a reference to a form - that would (or could) create a whole new form. You want to hold onto the form reference.

这是通过传递对表单的引用来完成的,但是谈论一个表单摆弄另一个表单上的控件是一个坏主意,因为它破坏了封装.但是表单是类(它在每个类的顶部都这么说),因此您可以添加 PropertiesMethods(Sub 和/或 Functions) 以方便来回传递信息.

This is done by passing a reference to the forms, but the talk of one form fiddling with the controls on another form is a bad idea because it breaks encapsulation. But forms are classes (it says so at the top of each one), so you can add Properties and Methods (Sub and/or Functions) to facilitate passing information back and forth.

最简单的方法是在构造函数中传递其他表单需要的任何内容:

The simplest way is to pass whatever the other form needs in the constructor:

' form 1 / "main" form / form to return to

Dim frm As New Form6(Me)

frm.Show()
Me.Hide()

为了使其工作,您需要修改目标表单上的构造函数(Sub New):

In order for this to work, you need to modify the constructor (Sub New) on the destination form:

Private frmReturnTo As Form
Public Sub New(f As Form)
    ' This call is required by the designer.
    InitializeComponent()

    frmReturnTo = f

End Sub

最好不要创建自己的构造函数,直到您熟悉它们.使用代码窗口顶部的下拉菜单:从左侧选择表单名称;从右侧选择新建.设计者向其中添加了不得更改的必需代码.

It is best not to create your own constructor until you are familiar with them. Use the drop downs at the top of the code window: from the left pick the form name; from the right, select New. The designer adds required code to them which must not be changed.

不要InitializeComponent() 调用之前添加任何代码,至少在您熟悉表单的生命周期之前.表单及其控件在运行之前不存在.

Do not add any code before the InitializeComponent() call at least until you are familiar with the life cycle of a form. The form and its controls do not exist until that runs.

返回主"形式:

If frmReturnTo IsNot Nothing Then
    frmReturnTo.Show()
End If

您可能希望删除一些标题栏按钮或将代码添加到表单 Closing 事件中,以便在用户通过系统菜单或按钮关闭时进行处理.

You may want to remove some of the title bar buttons or add code to the form Closing event to handle when the user closes via the system menu or buttons.

使用构造函数非常适用于表单必须具有一些数据才能完成其工作的情况.

Using the constructor is ideal for cases where there is some bit of data which the form must have in order to do its job.

这一切都很好,但是如何将数据传递给另一个表单呢?您也可以为此使用构造函数.为了传递say,一个字符串,一个整数和一个Point:

Thats all well and good, but what about passing data to another form? You can use the constructor for that too. In order to pass say, a string, integer and a Point:

' destination / second form:
Public Sub New(a As String, b As Int32, c As Point)
    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    Label1.Text = a
    Label2.Text = b.ToString
    Label3.Text = c.ToString

End Sub

这样称呼它:

' method two: pass data you want to share in the ctor
Dim frm As New frmData("hello", 6, New Point(150, 550))

frm.Show()

结果:

那很好,但是如果有大量数据,这种方式会变得很麻烦.另外,您可能希望更新来自调用/主表单的一些数据.为此,您可以在表单上创建 Properties 来处理数据:

Thats fine, but if there is a lots of data that way can get cumbersome. Plus, you may want to update some of the data from the calling/main form. For this you can create Properties on the form to handle the data:

Public Property Label1Text As String
    Get
        Return Me.Label1.Text
    End Get
    Set(value As String)
        Me.Label1.Text = value
    End Set
End Property

不是作为支持字段的私有变量,而是使用其中一个控件.这个名字有点不尽人意,因为它暴露了实现细节.因此,使用名称来描述数据代表什么,而不是它显示的位置.

Rather than a private variable to act as the backing field, one of the controls is used. The name leaves a bit to be desired as it exposes implementation details. So, use names which describe what the data represents rather than where it displays.

Public Property SpecialValue As Integer
    Get
        Return Integer.Parse(Me.Label2.Text)
    End Get
    Set(value As Integer)
        Me.Label2.Text = value.ToString
    End Set
End Property

Public Property SomePoint As Point
    Get
        Dim data = Me.Label3.Text.Split(","c)
        Return New Point(Convert.ToInt32(data(0)),
                         Convert.ToInt32(data(1))
                        )
    End Get
    Set(value As Point)
        Me.Label3.Text = value.X.ToString & "," & value.Y.ToString
    End Set
End Property

point 只是为了表明可以使用其他数据类型.从调用/原始/源表单设置这些值:

A point was used just to show that other data types can be used. Setting those values from the calling/original/source form:

Using frm As New Form6
    frm.Label1Text = "Ziggy"
    frm.SpecialValue = 42
    frm.SomePoint = New Point(111, 222)

    frm.ShowDialog()

    ' do stuff here with any changes
    Dim theint = frm.SpecialValue

End Using          ' dispose of dialog

目标控件很可能是供用户编辑的文本框.Property 包装器"允许您取回这些值,因此在本例中,使用了 Dialog.

The destination controls would well have been TextBoxes for the user to edit. The Property "wrappers" allow you to fetch those values back, so in this case, a Dialog was used.

您还可以使用方法作为将数据传递给第二个/辅助表单的一种方式.这里将传递一个 List(of T) 集合.在 child/display 表单中,添加了一个方法来接收它然后显示的数据.表示的任务是校对或查看过滤列表:

You can also use methods as a way to pass data to the second/helper form. Here a List(of T) collection will be passed. In the child/display form a method is added to receive the data which it then displays. The task represented is proofing or viewing a filtered list:

Public Sub UpdateDisplay(lst As List(Of SimpleItem), filter As String)
    DataGridView1.DataSource = lst
    Label1.Text = String.Format("{0} Total {1} Items", lst.Count, filter)
End Sub

在主/调用表单中:

' form level variable
Private frmDV As frmDataView

其他地方...也许在 Click 事件中:

elsewhere...perhaps in a Click event:

' myList is a simple list of items
' Users pick which color to filter on via a combo box

Dim filter As String
If cboListFilter.SelectedItem IsNot Nothing Then
    'Dim frmDV As New frmDataView
    If frmDV Is Nothing OrElse frmDV.IsDisposed Then
        frmDV = New frmDataView
    End If

    filter = cboListFilter.SelectedItem.ToString()
    ' apply the filter
    Dim tmpList = myList.Where(Function(w) w.Color = filter).ToList()
    frmDV.UpdateDisplay(tmpList, filter)

    frmDV.Show()
Else
    Return

End If

结果:

对于基于 DataBased 的应用程序,修改后的版本可以允许您在另一个表单上以详细形式显示 DataGridView 数据.您不需要第二个表单梯级 SQL 来添加或更新记录,然后主表单运行另一个查询来刷新".显示器.如果 DataSource 是由完全配置的 DataAdapter 备份的 DataTable,则传递 DataTable 并让子表单使用它添加、更改或删除.数据将自动出现在 DataTable 和 DataGridView` 中.

With DataBased apps a modified version of this can allow for the case where you display DataGridView data in detail form on another form. You need not have the second form rung SQL to add or update the record, and then the main form running another query to "refresh" the display. If the DataSource is a DataTable backed up by a fully configured DataAdapter, pass the DataTable and have the child form add, change or delete using that. The data will automagically be in the DataTable and DataGridView`.

还有其他方法可以做到这一点,但它们通常都归结为将某些东西从 A 传递到 B.哪种方法最好"?取决于应用程序的功能、用例和数据的性质.没有一种正确的方法或最好的方法.

There are other ways to do this, but they generally all boil down to passing something from A to B. Which way is "best" depends on what the app does, the use-case and the nature of the data. There is no one right way or best way.

例如,Properties 和在许多情况下的 Functions 允许 B 表单关闭反馈循环.对于数据库项,DataChanged 属性可能会告诉调用表单数据已添加或更改,以便表单知道使用 DataAdapter 更新数据库.

For instance, Properties and in many cases Functions allow the B Form to close the feedback loop. With DB items, a DataChanged property might tell the calling form that data was added or changed so that form knows to use the DataAdapter to update the db.

这篇关于如何将表单、对象或数据传递给第二个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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