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

标签 c# compact-framework windows-ce

我有包含“L1”的 string MyText

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

有什么方法可以使用 MyText 读取标签 L1 吗?

类似于:TMT = MyText.Text

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

提前致谢

最佳答案

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

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";
    }
}

关于c# - 如何将字符串转换为控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2938877/

相关文章:

c# - 尾递归优化发生在 visual studio 10 x64 调试中但不是在发布中?

c# - 使用 System.Diagnostics.Process.Start 运行程序会导致应用程序错误

c# - 在哪里部署配置文件和exe文件?

.net - 如何让移动应用保持领先?

Win CE 6 的 C 文件编译

c# - 多个检查点/重生区

c# - Linq to SQL - 忽略为空或零的搜索参数

visual-studio-2008 - JSON.NET Visual Studio 2008 和 .NET 3.5 Compact Framework

c# - 在 WinCE 上运行我的应用程序之前如何分配程序内存和存储空间?

c++ - 在另一个 COM 对象中创建一个 COM 对象