简体   繁体   English

如何使用字符串变量-c#获取标签名称

[英]How to get label name by using string variable -c#

I want to use a string variable to get a label name to change its text. 我想使用字符串变量来获取标签名称以更改其文本。 for example, I have the following code: 例如,我有以下代码:

string labelName = "lbl_text";
lbl_Heart_Rate.Invoke((MethodInvoker)(() => lbl_Heart_Rate.Text = displayValue.ToString()));

How do I use the string variable labelName to change the lbl_text's value? 如何使用字符串变量labelName更改lbl_text的值?

You have to find Label Control from the list of form control for a given name. 您必须从表单控件列表中找到给定名称的Label Control。

var control = this.Controls.OfType<Label>()
                           .FirstOrDefault(c=>c.Name == labelName");

if(control != null)
{
    // Now you can play with your logic.
    control.Invoke((MethodInvoker)(() => control.Text = displayValue.ToString())); 
}

I think the form has a function for this: Control.ControlCollection.Find 我认为表单具有此功能: Control.ControlCollection.Find

Full Code: 完整代码:

string labelName = "lbl_text";
TextBox lbl_text = this.Controls.Find(labelName , true).FirstOrDefault() as TextBox;
//You can access 'lbl_text' here...

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

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