Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have write a code which add Text boxes on button click on same page . and the code works pretty well. now i want to add multiple text boxes on other form say Form2 when i click on button on Form1.
Below is the code that i have written for addition of text boxes on same page . could you please help me to add the text boxes on other page.

What I have tried:

public partial class Form1:Form
{
static int j=1;
public Form1()
{
initializeComponent();
}
private void button1_Click(object sender, EventArgs e)

{
TextBox tb = new TextBox();
tb.text = " " + j;

Point p = new Point(20 + j,30* j);
tb.Location = p
this.Controls.Add(tb);
j++
}
}
Posted
Updated 30-Jul-16 4:57am

Don't.
Instead, use the same code on Form2 to add the textboxes there and call that from Form1:
C#
public partial class Form1:Form
    {
    ...
    private void button1_Click(object sender, EventArgs e)
        {
        Form2 f2 = new Form2();
        f2.AddTextBoxes();
        f2.Show();
        }
    }

C#
public partial class Form2:Form
    {
    ...
    public void AddTextBoxes(int count)
        {
        for (int i = 1; i <= count; i++)
            {
            TextBox tb = new TextBox();
            tb.text = " " + i;
            Point p = new Point(20 + i,30 * i);
            tb.Location = p
            Controls.Add(tb);
            }
        }
    }
That way, Form2 doesn't need to know that Form1 exists, and Form1 isn't locked into the internals of Form2.
 
Share this answer
 
v2
Comments
BillWoodruff 30-Jul-16 10:40am    
Appropriate music for this: https://www.youtube.com/watch?v=J1ia-OQThno

Note: I'd post the link to the original official video with Laetitia Casta, but that would not, perhaps, be SFW/KSS.

Oh boy, alarm bells are going off in my head. You don't keep a reference to the newly created instance of Form2 in Form1, and, in Form2, you don't keep a reference to the run-time created TextBoxes. The Form2 instance is now in outer-space; the TextBoxes on Form2 are now in inner-space :)

My head is a splode.
OriginalGriff 30-Jul-16 10:49am    
The form instance may or may not be relevant, and the text boxes (if needed) can be accessed via the Controls collection.
It's not ideal, but I didn't want to muck around with his code more than I had to to show him the outlines of what to do.
Your head is a splode? You is doing me a frighten!
OriginalGriff 30-Jul-16 10:53am    
I checked out the Laetitia Casta original, and you're probably right about the NSFW bit. I never saw it before, I must have lead a more sheltered life than I thought... :sigh:
Looking at your code, I see you do not keep a reference to the Textbox Controls you create at run-time. The moment the button1_Click code exits there is no variable 'tb.

So, if you wnat to read the Text in one of these created TextBoxes, you are going to have to find it, but, you haven't even given the TextBoxes a distinct identifying 'Name value: how will you find it if the Form has lots of other Controls on it ?

This is almost always a mistake, because you are going to want to ... in any real application ... at some point use run-time created Controls ... in the case of TextBoxes: read their Text content, set their Text content. And, you will probably want to attach some events to those run-time created Controls.

There are a variety of ways you could keep track of the TextBoxes; here's one idea:

a. create a new WinForm project: 'TestRunTimeControlCreation

b. put two Buttons on Form1: 'button1, 'button2

c. add a second Form to the project: 'Form2

d. replace the auto-generated code for Form1 with this:
C#
#region Region:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

#endregion

namespace TestRunTimeControlCreation
    public partial class Form1 : Form
    {
        private const string TextBoxNamePrefix = "tbx_";

        private readonly Dictionary<string, TextBox> _dctForm1NameToTBox = new Dictionary<string, TextBox>();

        private readonly Dictionary<string, TextBox> _dctForm2NameToTBox = new Dictionary<string, TextBox>();

        private readonly Form2 _form2Instance;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _form2Instance = new Form2();
            _form2Instance.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AddTextBoxToForm(this, 5);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AddTextBoxToForm(_form2Instance, 5);
        }

        public void AddTextBoxToForm(Form targetform, int nTextBox)
        {
            if (targetform == null || nTextBox < 1)
            {
                throw new ArgumentException("error in AddTextBoxToForm");
            }

            string namebase = string.Format("{0}{1}", targetform.Name, TextBoxNamePrefix);

            int tBxCnt;

            for (var x = 0; x < nTextBox; x++)
            {
                var newTextBox = new TextBox();
                newTextBox.Size = new Size(100,25);

                targetform.Controls.Add(newTextBox);

                if (targetform is Form1)
                {
                    tBxCnt = _dctForm1NameToTBox.Count;
                    newTextBox.Name = string.Format("{0}{1}", namebase, tBxCnt);

                    _dctForm1NameToTBox.Add(newTextBox.Name, newTextBox);
                    
                    // set location on Form1 here
                    newTextBox.Location = new Point(30, tBxCnt*40 + 60);
                }
                else if (targetform is Form2)
                {
                    tBxCnt = _dctForm2NameToTBox.Count;
                    newTextBox.Name = string.Format("{0}{1}", namebase, tBxCnt);

                    _dctForm2NameToTBox.Add(newTextBox.Name, newTextBox);

                    // set location on Form2 here
                    newTextBox.Location = new Point(30, tBxCnt*40 + 30);
                }
                else
                {
                    // something is wrong !
                    throw new ArgumentException(string.Format("invalid Form parameter{0}", targetform.Name));
                }

                newTextBox.Enter += OnTextBoxEnter;
                newTextBox.Leave += OnTextBoxLeave;

                // apply your own labeling scheme here ?
                newTextBox.Text = newTextBox.Name;
            }
        }

        private void OnTextBoxLeave(object sender, EventArgs eventArgs)
        {
            TextBox tBox = sender as TextBox;
            Console.WriteLine("Leave TextBox: {0} TextBox: {1} text: {2}", tBox.TopLevelControl.Name, tBox.Name, tBox.Text);
        }

        private void OnTextBoxEnter(object sender, EventArgs eventArgs)
        {
            TextBox tBox = sender as TextBox;
            Console.WriteLine("Enter TextBox: {0} TextBox: {1} text: {2}", tBox.TopLevelControl.Name, tBox.Name, tBox.Text);
        }
    }
}
Hook-up the EventHandlers for the two Buttons on Form1 to the 'button1 and 'button2 ClickHandlers.

Run the project. Click the Buttons, click in a few TextBoxes on Form1, click in a few TextBoxes on Form2. Then: examine what has been written to the Console (in the Visual Studio 'Output window).

Once you have created this kind of Dictionary structure to map the 'Name properties you have assigned to the run-time created TextBoxes, you can access any TextBox using the string 'Name key:
C#
TextBox getATbx;

if(_dctForm1NameToTBox.TryGetValue("Form1_Tbx_2", out getATbx))
{
    // getATbx got a Textbox
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900