我有一个带有 10 个文本框和确定按钮的表单。单击确定按钮时。我需要将文本框中的值存储到一个数组字符串中。
有人能帮助我吗?
我需要将文本框中的值存储到一个数组字符串中。
string[] array = this.Controls.OfType<TextBox>()
.Select(r=> r.Text)
.ToArray();
上面期望 TextBoxesForm
直接在容器内,而不是在容器内,如果它们在多个容器内,那么您应该递归地获取所有控件。
确保包含using System.Linq;
.
如果您使用的框架低于 .Net Framework 3.5。然后你可以使用一个简单的 foreach 循环,如:
List<string> list = new List<string>();
foreach(Control c in this.Controls)
{
if(c is TextBox)
list.Add((c as TextBox).Text);
}
(这将适用于 .Net 框架 2.0 以后)
要获取所有文本框,不仅是表单的直接子项(this)
Func<Control, IEnumerable<Control>> allControls = null;
allControls = c => new Control[] { c }.Concat(c.Controls.Cast<Control>().SelectMany(x => allControls(x)));
var all = allControls(this).OfType<TextBox>()
.Select(t => t.Text)
.ToList();