1

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?

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
QKWS
  • 1,069
  • 9
  • 22
  • 41

2 Answers2

6

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)

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    Smart! my alternative solution is to manually create the textboxes in code, instead of using the designer, and then the rest is trivial. – David May 23 '13 at 07:14
  • Habib, I am having this error 'System.Windows.Forms.Control.ControlCollection' does not contain a definition for 'OfType' – QKWS May 23 '13 at 07:43
  • @QKWS, make sure you include `using System.Linq;` at the top. – Habib May 23 '13 at 07:43
  • @Habib May I know the assembly reference for System.Linq? I am having this error:The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) – QKWS May 23 '13 at 07:47
  • @QKWS, what is the .Net framework you are using, it is supported from .Net 3.5 onward. – Habib May 23 '13 at 07:51
  • @QKWS, just updated the answer which is support in lower version of .Net framework as well. – Habib May 23 '13 at 07:55
  • Error: The type or namespace name 'Textbox' could not be found (are you missing a using directive or an assembly reference?) – QKWS May 23 '13 at 08:36
  • `Error: The type or namespace name 'Textbox' could not be found (are you missing a using directive or an assembly reference?)` OMG. and I provided a recursive lambda solution. @QKWS replace `Textbox` with `TextBox` – I4V May 23 '13 at 09:10
2

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();
I4V
  • 34,891
  • 6
  • 67
  • 79