Maya Noorallah Diab
Maya Noorallah Diab

Reputation: 19

How to get values form programmatic text boxes?

I have code that programmatically add new labels and textboxes to a panel :

 Label newLabel;
 TextBox newTextBox;
 int txtBoxStartPosition = 75;
 int txtBoxStartPositionV = 25;

   for (int i = 0; i<LB.SelectedItems.Count; i++)
        {
            newLabel = new Label();
            newTextBox = new TextBox();
            newTextBox.Location = new System.Drawing.Point(
                                  txtBoxStartPosition + 150,
                                  txtBoxStartPositionV);
            newTextBox.Size = new System.Drawing.Size(70, 40);
            newLabel.Location = new System.Drawing.Point(
                                txtBoxStartPosition, 
                                txtBoxStartPositionV);
            newLabel.Size = new System.Drawing.Size(120, 40);
            newTextBox.Text = "0";
            newLabel.Text = LB.SelectedItems[i].ToString();
            this.panel1.Controls.Add(newTextBox);
            this.panel1.Controls.Add(newLabel);
            txtBoxStartPositionV += 50;
        }   

After run ... the user will enter values in the textboxes and he will click on a "ok" button. How can I get these values in : void button1_Click(object sender, EventArgs e) function ????

Upvotes: 0

Views: 65

Answers (1)

Habib
Habib

Reputation: 223402

Since you are adding all your TextBox's to panel1 you can access them like:

var allTextBoxesInPanel1 = panel1.Controls.OfType<TextBox>();

Then you can iterate the result and get value for each TextBox.

foreach(TextBox textBox in allTextBoxesInPanel1)
{
    Console.WriteLine(textBox.Text);
}

Upvotes: 4

Related Questions