Khandkar Asif Hossain
Khandkar Asif Hossain

Reputation: 75

How to dynamically add integer values from textbox to a int array in C#

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

Upvotes: 0

Views: 454

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 1

Related Questions