如何访问 C# 中动态创建的文本框,其名称以字符串形式提供?

发布于 2024-08-01 19:15:08 字数 88 浏览 1 评论 0原文

我有一个动态创建的(运行时创建)文本框,其名称可作为字符串使用。我想要做的是像普通文本框一样访问此文本框。任何人都可以告诉我如何将其转换为文本框或任何其他解决方案

I have a dynamically created (runtime creation) textbox whose name is available as a string.What i want to do is access this textbox like we do as normal textboxes .Can any one tell me how to cast it as textbox or any other solution

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

残花月 2024-08-08 19:15:08

如果您知道文本框及其父控件的名称,则可以这样做:

TextBox tb = (TextBox )parent.Controls["name"];

If you know the name of the textbox and its parent controls, you can do like this:

TextBox tb = (TextBox )parent.Controls["name"];
脸赞 2024-08-08 19:15:08

除了 Iordan 的答案之外,如果您不知道文本框在表单上的确切位置,那么此扩展方法应该会有很大帮助。 请注意,Form 也从 Control 继承,因此您可以从该控件或表单上的任何控件调用它。

public static class ExtensionMethods
{
    public static Control FindControl(this Control root, string name)
    {
        foreach (Control c in root.Controls)
        {
            // Check this control
            if (c.Name == name) return c;

            // Check this controls subcontrols
            Control tmp = c.FindControl(name);
            if (tmp != null) return tmp;
        }

        return null;
    }
}

如果这仍然对您来说不够灵活,那么您可以迭代System.Windows.Forms.Application.OpenForms

In addition to Iordan's answer, if you don't know exactly where on your form the textbox is, then this extension method should help alot. Note, Form's inherit from Control somewhere down the track too, so you can call it from that, or any control on your form.

public static class ExtensionMethods
{
    public static Control FindControl(this Control root, string name)
    {
        foreach (Control c in root.Controls)
        {
            // Check this control
            if (c.Name == name) return c;

            // Check this controls subcontrols
            Control tmp = c.FindControl(name);
            if (tmp != null) return tmp;
        }

        return null;
    }
}

If this still isn't flexible enough for you, then you can iterate over System.Windows.Forms.Application.OpenForms

静待花开 2024-08-08 19:15:08

由于您似乎可以控制创建过程,因此请将对其的引用放入字典中。

TextBox txt = DynamicCreate(name);
map[name] = txt;
this.Controls.Add(txt);

您所要做的就是在字典中查找它,而不是循环遍历表单上的所有控件。

TextBox txt = 地图["名称"];

Since you seem to have control over the creation process, put a reference to it in a dictionary.

TextBox txt = DynamicCreate(name);
map[name] = txt;
this.Controls.Add(txt);

All you have to do is look it up in your dictionary, instead of loop through all the controls on the form.

TextBox txt = map["name"];

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文