vb.net在表单之间传递文本框。 [英] vb.net Pass Textbox Between forms.

查看:90
本文介绍了vb.net在表单之间传递文本框。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种表格。在Form1上,我想在加载时将文本框值传递给Form 2。我认为这是可行的。将加载并运行Form1,并在form1中填充数据。我在form1中公开了文本框的属性。然后,我尝试在form2中使用该公开属性。

I have 2 forms. On Form1 I want to pass the textbox value to form 2 on load. This is what I thought would work. Form1 will be loaded and running and data will be populated in form1. I am exposing the property of the text box in form1. Then I am trying to use that exposed property in form2.

Public Class form1

Public ReadOnly Property GetTextBox() As String
    Get
        Return txtbox1.Value
    End Get
End Property

在form2上

 Dim X As form1
 Me.TextBox1.Text = X.GetTextBox


推荐答案

有几种方法可以给这只猫剥皮。

There are a handful of ways to skin this cat.

最简单的方法是为 Form2 创建第二个(或替换现有的)构造函数,该构造函数接受 string 作为参数。然后,当 Form1 创建 Form2 时,您可以以这种方式传递参数。

The simplest would be to create a second (or replace the existing) constructor for Form2 that accepts a string as an parameter. Then when Form1 creates Form2 you can pass the argument that way.

Public Class Form2
    Sub New(ByVal txt As String)
        InitializeComponent()
        Me.TextBox1.Text = txt
End Sub
End Class

然后使用 Form1 您可能会像 Dim f2 As Form2 = New Form2(myTextBox.Text)

老实说,其他方法与此基本相同,除了您可以将 Textbox 本身作为构造函数的参数传递,甚至可以将 Form1 并在构造函数中为 Dim X As Form1 = theForm 赋值。一般来说,如果您只需要 Textbox.Text ,那么您只应在其中接受 string 构造函数。如果您不需要所有控件或表单,则没有理由公开它们!

The other ways are honestly basically the same as this, except you could pass the Textbox itself as an argument to the constructor, or even Form1 and assign Dim X As Form1 = theForm in the constructor. Generally speaking, if you don't need anything more than just Textbox.Text then you should only accept a string in the constructor. No reason to expose an entire control or form if you don't need all of it!

您当前的代码非常接近,但是正如Plutonix注释您的 Form2 X 属性仅仅是 Form1 ,而不是应用程序正在显示的实际实例。

Your current code is pretty close, but as Plutonix commented your Form2's X property is just another instance of Form1, not the actual instance that's being displayed by the application.

这篇关于vb.net在表单之间传递文本框。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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