我面临一个奇怪的问题
我有3种表格:MainForm
,Form1
,Form2
MainForm
有1个小组:Panel1
Form1
有1个标签:NameLbl
和按钮:ChangeBtn
Form2
有1个文本框:NameTxt
和Button:SaveBtn
我使用以下代码在form1
Panel1
内打开mainform
Panel1.Controls.Clear()
Dim FormInPanel As New Form1()
FormInPanel.TopLevel = False
Panel1.Controls.Add(FormInPanel)
FormInPanel.Show()
在ChangeBtn.Click
Form2
上打开showdialog
我希望NameLbl.tex
在NameLbl.text
被点击时更改为SaveBtn
但普通代码无效。
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Form1.NameLbl.text=NameTxt.text
End Sub
我该怎么办?有什么建议?鉴于我需要出于某些原因打开面板中的表格
请记住,这只是一个例子。我在Form1中有多个控件,我想在form2上更改.SaveBtn.click
我也尝试了这个,但它没有做任何事
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
For Each c As Control In MainForm.Panel1.Controls(0).Controls
If c.Name="NameLbl" Then
c.Text = NameTxt.Text
End If
Next
End Sub
请有人告诉我它是怎么做的!
答案 0 :(得分:0)
Form2似乎没有任何与Form1或MainForm的连接。您需要从Form2中引发一个事件,MainForm处理或另一个类处理并可以传递给MainForm
编辑:
抱歉,我刚刚看到您如何调用Form2。调用ShowDialog()后,有很多方法可以从Form2中获取值。一种是创建一个名为Result的属性,如果ShowDialog()== DialogResult.OK则检查Result。如下所示。
Public Class Form2
Inherits System.Windows.Forms.Form
Public Property Result() As String
Get
Return m_Result
End Get
Set
m_Result = Value
End Set
End Property
Private m_Result As String
End Class
Public Class Form1
Inherits System.Windows.Forms.Form
Public ChangeBtn As Button
Public NameLbl As Label
Public Sub New()
Me.ChangeBtn = New Button()
AddHandler Me.ChangeBtn.Click, AddressOf ChangeBtn_Click
Me.NameLbl = New Label()
End Sub
Private Sub ChangeBtn_Click(sender As Object, e As EventArgs)
Dim form As New Form2()
Dim dr = New form.ShowDialog()
If dr = DialogResult.OK Then
Me.NameLbl.Text = form.Result
End If
End Sub
End Class
我想补充一点,如果您计划将此应用程序发展得更大,那么您将遇到维护问题。如果您有兴趣,请查看一些处理UI逻辑的模式,如MVC,MVP,MVVM。
答案 1 :(得分:0)
你可以试试这段代码:
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
panel1.Controls(0).NameLbl.text=NameTxt.text '"0" is the index of forminpanel in panel1,maybe it need to change.
End Sub
答案 2 :(得分:0)
Form1 包含在 Panel1 中,因此您无法通过
访问它 Form1.
从 Form2 只能看到 MainForm :
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
For Each c As Control In MainForm.Panel1.Controls(0).Controls
If TypeOf c Is TextBox Then
c.Text = NameTxt.Text
End If
Next
End Sub
答案 3 :(得分:0)
试试这个:
For Each form1 As Form1 In MainForm.OwnedForms.OfType(Of Form1)
Form1.NameLbl.text = NameTxt.text
Next
答案 4 :(得分:0)
我遇到了同样的问题,并且已经解决了这个问题
Dim f As FormInPanel
f = Form.Panel1.Controls(0)
f.transection = True
f.NameLbl.text=NameTxt.text