如何将字符串转换为控件?

时间:2010-05-30 13:51:53

标签: c# compact-framework windows-ce

我有string MyText持有“L1”

我有标签控制,他的名字是“L1”

有没有办法用MyText读取标签L1?

类似于:TMT = MyText.Text

或:TMT = ((Control)MyText.ToString()).Text;

提前致谢

3 个答案:

答案 0 :(得分:4)

查找具有指定名称的控件:

var arr = this.Controls.Where(c => c.Name == "Name");
var c = arr.FirstOrDefault();

或在指定类型的控件内搜索:

var arr = this.Controls.OfType<Label>();
var c = arr.FirstOrDefault();

修改

如果你有一个控件名称数组,你可以找到它们:

var names = new[] { "C1", "C2", "C3" };

// search for specified names only within textboxes
var controls = this.Controls
    .OfType<TextBox>()
    .Where(c => names.Contains(c.Name));

// put the search result into a Dictionary<TextBox, string>
var dic = controls.ToDictionary(k => k, v => v.Text); 

(以上所有内容都需要.NET 3.5)

如果你没有它,你可以做下一步:

Control[] controls = this.Controls.Find("MyControl1");
if(controls.Lenght == 1) // 0 means not found, more - there are several controls with the same name
{
    TextBox control = controls[0] as TextBox;
    if(control != null)
    {
        control.Text = "Hello";
    }
}

答案 1 :(得分:2)

更简单的方法是做这样的事情:

string TMT = "myButton";    
// later in the code ...
(Controls[TMT] as Button).Text = "Hullo";
例如

答案 2 :(得分:1)

您可以这样做:

        foreach (var c in this.Controls)
        {
            if (c is Label)
            {
                var x = (Label)c;
                if (x.Name == "label1")
                {
                    x.Text = "WE FOUND YOU";
                    break;
                }
            }
        }

然而,最佳做法是避免这种情况......如果您可以推测出更多为什么需要这种情况,那么可能会有更好的解决方案。

- 编辑:感谢您注意到/ typeof ..