更改面板内窗体的控件



我面临一个奇怪的问题

我有三种形式:MainFormForm1Form2
MainForm有一个面板:Panel1
Form1有1个标签:NameLbl和按钮:ChangeBtn
Form2有1个文本框:NameTxt和按钮:SaveBtn

我使用以下代码在mainform 中打开Panel1内部的form1

 Panel1.Controls.Clear()
 Dim FormInPanel As New Form1()
 FormInPanel.TopLevel = False
 Panel1.Controls.Add(FormInPanel)
 FormInPanel.Show()

ChangeBtn.Click上,Form2showdialog的形式打开
我希望单击SaveBtnNameLbl.text更改为NameLbl.text,但正常代码不起作用。

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上更改这些控件。保存Btn。单击

我也尝试过,但没有任何效果

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

请有人告诉我它是怎么做的!

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。

您可以尝试以下代码:

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

Form1包含在Panel1中,因此您无法通过访问它

  Form1.

只有主窗体窗体2可见:

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

试试这个:

For Each form1 As Form1 In MainForm.OwnedForms.OfType(Of Form1)
    Form1.NameLbl.text = NameTxt.text
Next

我也遇到过同样的问题,我已经修复了这个

     Dim f As FormInPanel
     f = Form.Panel1.Controls(0)
     f.transection = True
     f.NameLbl.text=NameTxt.text

相关内容

  • 没有找到相关文章

最新更新