ajjar
ajjar

Reputation: 3

Input from C# Dynamically Created Text Boxes

I am using some code I found in one of the solutions here to dynamically generate labels and text boxes on a form while the program is running. The code to generate the labels and boxes works fine. My problem is that I will need to be able to do something with the input from the user into those text boxes which were dynamically created, but I'm not sure how to access the user's input in order to define it as a variable. Thank you for your help.

The code I am using is as follows:

private void button2_Click(object sender, EventArgs e)
    {
        int intGroups = Convert.ToInt32(maskedTextBox1.Text);
        int n = intGroups;
        for (int i = 1; i <= n; i++)
        {
            //Retrieved from http://stackoverflow.com/questions/15008871/how-to-create-many-labels-and-textboxes-dynamically-depending-on-the-value-of-an                
            //Create label
            Label portTypeLabel = new Label();
            portTypeLabel.Text = String.Format("Port Type (FastEthernet/GigabitEthernet) {0}", i);

            Label portGroupLabel = new Label();
            portTypeLabel.Text = String.Format("Port Group (the first number before the slash, usually 1) {0}", i);

            Label startIntNumLabel = new Label();
            portTypeLabel.Text = String.Format("Group {0} starting interface number", i);

                            //Position label on screen
            portTypeLabel.Left = 10;
            portTypeLabel.Top = (i) * 20;
            /* Must add the rest of the code for displaying the labels here
            */
            //Create textbox
            TextBox textBox = new TextBox();
            ComboBox combo = new ComboBox();
            //Position textbox on screen
            textBox.Left = 120;
            textBox.Top = (i) * 20;
            combo.Left = 120;
            combo.Top = (i) * 20;
            //Add controls to form
            this.Controls.Add(portTypeLabel);
            this.Controls.Add(textBox);
            this.Controls.Add(combo);
        }

Upvotes: 0

Views: 3313

Answers (1)

Ofer Haviv
Ofer Haviv

Reputation: 39

First, you need to give the controls some names to access them easily.

TextBox textBox = new TextBox();
textBox.Name = "textbox" + i.ToString();

Second, if you need to create method for selection you will need to define event

textBox.TextChanged += new System.EventHandler(this.TextChanged);

In this method you can put switch..case to check with textbox fire the event (maybe using the number at the end).

void TextChanged(object sender, EventArgs e){
    TextBox t = (TextBox)sender;
    // t is the textbox you referred
    MessageBox.Show(t.Name);
}

Upvotes: 1

Related Questions