有没有人知道如何从父表单调用任何对象(标签,文本框,面板)。例如,我有一个表格A,这个表格有一个标签L,文本框T和按钮B.我可以通过一个函数(公共DoSomething(表格f))传递整个表格,然后改变标签L的属性,功能DoSomething中的文本框T和按钮B?
class DoSomething{
private Form parentForm;
public DoSomething(Form f) {
parentForm = f;
// HERE I WOULD LIKE TO CHANGE PROPERTIES OF LABEL L, BUTTON B
}
}
答案 0 :(得分: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...
答案 1 :(得分: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
答案 2 :(得分:0)
尝试将父表单属性的控件设置为Modifier to Public
。
以儿童形式,用作
parentForm.btnA.Name="ButtonB";
希望它有效!