动态创建多个文本框 C#

dynamically create multiple textboxes C#(动态创建多个文本框 C#)
本文介绍了动态创建多个文本框 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.但是我所有文本框的值都是空的.

This is my code. But all my textboxes's value is just null.

    public void createTxtTeamNames()
    {
        TextBox[] txtTeamNames = new TextBox[teams];
        int i = 0;
        foreach (TextBox txt in txtTeamNames)
        {
            string name = "TeamNumber" + i.ToString();
            txt.Name = name;
            txt.Text = name;
            txt.Location = new Point(172, 32 + (i * 28));
            txt.Visible = true;
            i++;
        }
    }

感谢您的帮助.

推荐答案

数组创建调用只是将元素初始化为null.您需要单独创建它们.

The array creation call just initializes the elements to null. You need to individually create them.

TextBox[] txtTeamNames = new TextBox[teams];
for (int i = 0; i < txtTeamNames.Length; i++) {
  var txt = new TextBox();
  txtTeamNames[i] = txt;
  txt.Name = name;
  txt.Text = name;
  txt.Location = new Point(172, 32 + (i * 28));
  txt.Visible = true;
}

注意:正如一些人所指出的,为了使这段代码有意义,您需要将每个 TextBox 添加到父 Control.例如 this.Controls.Add(txt).

Note: As several people have pointed out in order for this code to be meaningful you will need to add each TextBox to a parent Control. eg this.Controls.Add(txt).

这篇关于动态创建多个文本框 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)