2012-05-04 69 views
0

有誰知道如何從父窗體調用任何對象(標籤,文本框,面板)。例如,我有一個表單A,這個表單有一個標籤L,文本框T和按鈕B.是否通過函數(public DoSomething(Form f))傳遞整個表單,然後更改標籤L的屬性, Textbox T和Button B在函數DoSomething中?更改父窗體中任何控件的屬性

class DoSomething{ 
private Form parentForm; 
public DoSomething(Form f) { 
    parentForm = f; 
    // HERE I WOULD LIKE TO CHANGE PROPERTIES OF LABEL L, BUTTON B 
} 
} 
+0

請不要用「C#」等來標題。這就是標籤的用途。 –

回答

0

您可以通過所有表單控件進行迭代,並更改屬性爲每個控件:

foreach (Control c in parentForm.Controls) 
{ 
    if (c is Label && c.Name == "L") 
    { 
     // Do label stuff here 
    } 
    else if (c is TextBox && c.Name == "T") 
    { 
     // Do text box stuff here 
    } 
    if (c is Button && c.Name == "B") 
    { 
     // Do button stuff here 
    } 
} 

如果你想通過自己的名字,找到控制,你可以試試這個:

Label L = (Label)parentForm.Controls.Find("L"); 
TextBox T = (TextBox)parentForm.Controls.Find("T"); 
Button B = (Button)parentForm.Controls.Find("B"); 

// Do stuff with L, T and B here... 
0

您面臨的問題是類窗體不會說明您感興趣的屬性。

Indise DoSomething的,你必須將表格轉換爲原始類型來訪問它的控制:

if (f is Form1) 
{ 
    Form1 f1 = f as Form1; 
    f1.C... // here all the properties of the class form1 Are available. 
} 

如果所有的形式有共同的屬性,你可以創建一個接口,而在所有的形式實現它。而你DoSomething的參數類型設置爲接口類型:

void DoSomething(IFomrInterface fi) 
{ 
    fi.C... // this will have all the propertie savailabel in the interface 
} 

第二種解決方案是比較通用的。所有表格應實現的接口:

class Form1: Form, IFormInterface 
0

父母嘗試將控制器設定形成屬性Modifier to Public

在孩子的形式,用作

parentForm.btnA.Name="ButtonB"; 

希望工程!

相關問題