0

I want to create a form with a button where button can create a set of components(2 text boxes, 1 label). I want the value entered in the text boxes to be stored into a int array.

I have worked this far Button Click Event

 private void button1_Click(object sender, EventArgs e)
    {

        AddNewLabel();
        AddNewTextBox1();
        AddNewTextBox2();
    }

Adds Textboxes

 public System.Windows.Forms.TextBox AddNewTextBox1()
    {
        System.Windows.Forms.TextBox txt1 = new System.Windows.Forms.TextBox();
        this.Controls.Add(txt1);
        txt1.Top = txtBoxCounter * 28;
        txt1.Left = 125;
        string txtName1 = "txtLL" + txtBoxCounter;
        txt1.Name = txtName1;
        string txtValue1 = txt1.Text;
        lowerLimit[txtBoxCounter-1] = Int32.Parse(txtValue1);
        return (txt1);


    }

Adds Labels

public System.Windows.Forms.Label AddNewLabel()
    {
        System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
        this.Controls.Add(lbl);
        lbl.Top = lblCounter * 28;
        lbl.Left = 15;
        lbl.Text = "Range" + lblCounter;
        lblCounter = lblCounter + 1;
        return (lbl);
    }

After Start Debbuging Inital Form

After Button Click After Button Click

2
  • 1
    Why not just create a user control containing a couple of text boxes and a label? Commented May 13, 2018 at 14:26
  • 4
    Creating your own grid control like this is a Very Bad idea. Use DataGridView instead. Many other ones out there. Commented May 13, 2018 at 14:33

1 Answer 1

1

There are several approaches to this: you could store TextBox objects that you create in a collection in an instance variable on the form, or since text boxes are already added to this.Controls, you could walk them dynamically.

The approach is up to you; here is an example of using the second approach:

var total = this.Controls
    .OfType<TextBox>
    .Sum(tb => {
        int val;
        if (int.TryParse(tb.Text, out val)) {
            return val;
        }
        return 0;
    });

Note: You need to import System.Linq for this approach to compile.

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

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.