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?

3
  • 2
    Did you try anything? Please read FAQ and How to Ask Commented May 23, 2013 at 7:11
  • Can you show some code? Do you know how to read data from a text box and do you know how to store data in an array? Commented May 23, 2013 at 7:23
  • string[] list = new list[9]; list[0] = textbox1.Text; Commented May 23, 2013 at 7:32

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

8 Comments

Smart! my alternative solution is to manually create the textboxes in code, instead of using the designer, and then the rest is trivial.
Habib, I am having this error 'System.Windows.Forms.Control.ControlCollection' does not contain a definition for 'OfType'
@QKWS, make sure you include using System.Linq; at the top.
@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, what is the .Net framework you are using, it is supported from .Net 3.5 onward.
|
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.