简体   繁体   English

如何访问添加到面板的控件?

[英]How to access to a Control added to a panel?

I`m trying to modify on job the Text of a label (label.Text) that I have previously added to a panel (MyPanel.Controls.Add(MyLabel).我正在尝试修改之前添加到面板 (MyPanel.Controls.Add(MyLabel) 的 label (label.Text) 的文本。

I add the label to the panel in a function:我将 label 添加到 function 的面板中:

public PanelEx nameoffunction()
{
.
.
MyPanel.Controls.Add(MyLabel);
return MyPanel;
.
.
}
MyPanelWithControl = nameoffunction();

Now I have in MyPanelWithControl the panel with a label.现在我在MyPanelWithControl的面板。 How can I now access to the label previously added to modify one of its fields?我现在如何访问之前添加的 label 以修改其字段之一?

You can find a control using its Name property:您可以使用其 Name 属性找到一个控件:

MyLabel.Name = "label1";
MyPanel.Controls.Add(MyLabel);
...
MyPanel.Controls["label1"].Text = "updated text";

However, this approach can lead to problems later if you make changes to your user interface.但是,如果您对用户界面进行更改,这种方法可能会在以后导致问题。 If you moved the label to another panel, or changed its name, then the code which tries to find it using the name would still compile but cause an error at runtime.如果您将 label 移动到另一个面板,或更改其名称,则尝试使用该名称查找它的代码仍会编译,但在运行时会导致错误。 For long-term projects it's preferable to store references to controls as properties:对于长期项目,最好将控件的引用存储为属性:

public class PanelEx : Panel {
    ...
    public Label MyLabel { get; set; }
}

public PanelEx nameoffunction() {
    ...
    MyPanel.MyLabel = MyLabel;
    return MyPanel;
}

And then you can access the Label directly from the panel object:然后您可以直接从面板 object 访问 Label:

MyPanel.MyLabel.Text = "updated text";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM