簡體   English   中英

如何在C#2008/2010中訪問Form1中的Form2控件

[英]How to access the controls of form2 in form1 in C# 2008/2010

如何在Form1中訪問Form2的控件

我也想在Form1本身中為Form2控件創建事件。 如何做到這一點? 請使用C#2008 Windows窗體為我提供完整的代碼。

好的,假設您有frmMain和frmSettings。 您希望frmSettings更新,例如frmMain上的標簽。 這就是我的解決方法。

步驟1.在您的frmMain.Designer.cs中,將label(或其他控件)范圍更改為public。

例。

public System.Windows.Forms.GroupBox groupBox2;
public System.Windows.Forms.Label label8;

現在很容易嗎?

步驟2.在您的frmSettings中聲明此內容。

protected frmMain frmMain;

    public frmSettings(frmMain frmMain)
    {
        this.frmMain = frmMain;
    }

現在,只需有趣地改變事物即可。 喜歡:

frmMain.label8.Text="Changed from frmSettings";

最佳實踐是希望設置要公開的控件屬性的屬性,以使任何人都不能真正干擾表單的期望行為。

public partial class SecondaryForm {
    // Let's suppose you have put a TextBox control in design mode named txtCusomerName.
    public string CustomerName {
        set {
            this.txtCustomerName.Text = value.Trim();
        }
    }
}

public partial class MainForm {
    // Suppose you have a button to show a form with the customer name.
    private btnShowCustomerName_Click(object sender, EventArgs e) {
        SecondaryForm f
        f.CustomerName = "Acme inc,";
        f.ShowDialog();
    }
}

這有幫助嗎?

從表單1中打開表單2,並使用打開它的變量來訪問表單。例如。

在表格1中

Form2 secondForm = new Form2();
Form2.Show();

secondForm.somePublicControl.Text = "test";
MessageBox.Show(secondForm.somePublicVariable);

您是否真的要以其他形式訪問控件,還是要對另一種形式使用的數據的值更改做出反應? 后一種情況可以通過將控件綁定到全局模型數據並使用INotifyPropertyChanged接口發出信號/監聽數據更改來實現。

今天對我有幫助的是呼叫表格1,表格2功能:

f2 frm = new f2();
frm.ShowDialog(this);
MessageBox.Show(frm.proc); // frm.proc is variable public in Form2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM