Windows Forms中如何获取动态生成TextBox控件的输入内容
WinForm 动态生成TextBox获取用户输入的解决方案
方法1:全局集合存储实例(最推荐)
在窗体类中定义类级别的List<TextBox>存储所有动态生成的文本框实例,后续直接从集合中读取即可:
- 首先在Form类中声明集合:
// 声明在Form类内部、方法外作为类成员 private List<TextBox> _dynamicTextBoxList = new List<TextBox>();
- 修改动态生成TextBox的代码,将实例加入集合:
TextBox txtbox = new TextBox(); this.positionY += 40; txtbox.Location = new System.Drawing.Point(this.positionX, this.positionY); // 可选:给控件设置唯一Name方便后续精准定位 txtbox.Name = $"dynamicTxt_{_dynamicTextBoxList.Count}"; this.Controls.Add(txtbox); // 加入全局集合 _dynamicTextBoxList.Add(txtbox);
- 读取所有动态文本框的输入内容:
foreach (TextBox txt in _dynamicTextBoxList) { string inputContent = txt.Text; // 此处编写你的业务逻辑处理输入内容 }
方法2:遍历窗体控件集合筛选
如果不想额外维护集合,可以在生成时给动态TextBox设置统一标记,后续从窗体控件集合中过滤读取:
- 动态生成时添加标记,比如设置Tag属性:
TextBox txtbox = new TextBox(); this.positionY += 40; txtbox.Location = new System.Drawing.Point(this.positionX, this.positionY); // 设置统一标记区分设计时创建的文本框 txtbox.Tag = "DynamicCreated"; this.Controls.Add(txtbox);
- 遍历筛选读取内容:
foreach (Control ctl in this.Controls) { // 筛选标记为DynamicCreated的TextBox if (ctl is TextBox txt && txt.Tag?.ToString() == "DynamicCreated") { string inputContent = txt.Text; // 处理输入内容 } }
扩展:精准获取单个动态TextBox内容
如果给动态生成的TextBox设置了唯一Name属性,可以直接通过Name查找:
// 查找Name为dynamicTxt_1的动态文本框 TextBox targetTxt = this.Controls.Find("dynamicTxt_1", true).FirstOrDefault() as TextBox; if (targetTxt != null) { string input = targetTxt.Text; }
内容的提问来源于stack exchange,提问作者JuRi-2020
相关产品推荐
相关产品推荐

