I have a form with 10 TextBoxes and OK button. When the OK button was clicked. I need to store the values from the textboxes to a string of array.
Can someone help me please?
I have a form with 10 TextBoxes and OK button. When the OK button was clicked. I need to store the values from the textboxes to a string of array.
Can someone help me please?
I need to store the values from the textboxes to a string of array.
string[] array = this.Controls.OfType<TextBox>()
.Select(r=> r.Text)
.ToArray();
The above expects the TextBoxes to be on the Form
directly, not inside a container, if they are inside multiple containers then you should get all the controls recursively.
Make sure you include using System.Linq;
.
If you are using lower frameworks than .Net Framework 3.5. Then you can use a simple foreach loop like:
List<string> list = new List<string>();
foreach(Control c in this.Controls)
{
if(c is TextBox)
list.Add((c as TextBox).Text);
}
(this would work with .Net framework 2.0 onward)
To get all textboxes not only the direct childs of the form (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();