[英]Interaction between forms — How to change a control of a form from another form?
[英]how to change a control property from another form
我在 Windows 窗體應用程序中有兩個窗體。 讓我們稱它們為“第一形式”和“第二形式”。 我想通過單擊第二個表單上的按鈕,更改第一個表單的一個控件的屬性。 我為此定義了一個事件。 我的意思是當我點擊第二個表單的按鈕時,第一個表單中的一個方法被調用。 這是方法:
// changes the visibility of the specified control
public void change_visibility()
{
this.new_customer_label.Visible = true;
}
但是當我在此方法上設置斷點並在執行后檢查該值時。 屬性沒變。 怎么了? 提前致謝
注意:在第二個表單按鈕的點擊事件中,我也關閉了表單。
所以首先,打開Form1.designer.cs
並將控件更改為public
Form1
這將打開 Form 2。
Form2 frm2 = new Form2();
frm2.Owner = this;
frm2.Show();
Form2
這將更改 Form 1 中控件的屬性
(this.Owner as Form1).label1.Visible = true;
以下是您可以執行的操作的示例:
class Form1 : Form {
private Label labelInForm1;
public string LabelText {
get { return labelInForm1.Text; }
set { labelInForm1.Text = value; }
}
}
class Form2 : Form {
Form1 form1; // Set by the property
private Form1 Form1 {
get { return form1; }
set { form1 = value; }
}
private ChangeVisibility()
{
Form1.labelInForm1.Visible = true;
}
}
“注意:在第二個表單按鈕的點擊事件中,我也關閉了表單。”
那么使用 ShowDialog() 而不是 Show() 來顯示第二個表單可能是一個更好的設計。 就像是:
Form2 f2 = new Form2();
f2.ShowDialog(); // code STOPS here until "f2" is closed
this.new_customer_label.Visible = true;
默認情況下,設計器在“Form1.Designer.cs”類中生成代碼。 在那里,您可以看到所有控件都設置為私有,將它們更改為公開,然后重試...
當您在互聯網上搜索這個問題時,您會發現不同的解決方案,但我認為最好的解決方案是將控件公開,然后您可以從任何形式訪問這些控件。 請遵循這些說明。
Form Form2 objForm=new Form2();
objForm.new_customer_label.Visible=true;
我希望這對你有幫助!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.