9

I am learning c#. I want to create some controls dynamically. Here is the code that I am trying to create new elements on form dynamically, but it doesn't do anything. Please help me to solve this problem.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

    namespace Sampless
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int n = 4;

        private void btnDisplay_Click(object sender, EventArgs e)
        {
            TextBox[] textBox = new TextBox[n];
            Label[] label = new Label[n];

            for (int i = 0; i < n; i++)
            {
                textBox[i] = new TextBox();
                textBox[i].Name = "n" + i;
                textBox[i].Text = "n" + i;

                label[i] = new Label();
                label[i].Name = "n" + i;
                label[i].Text = "n" + i;
            }

            for (int i = 0; i < n; i++)
            {
                this.Controls.Add(textBox[i]);
                this.Controls.Add(label[i]);
            }
        }
    }
}
3
  • This looks like a job for a repeater. Could you use a generic list of your controls and bind it to a repeater? Commented Feb 7, 2014 at 17:16
  • probable duplicate at stackoverflow.com/questions/9368748/… Commented Feb 7, 2014 at 17:22
  • Please provide a better statement of the problem than “it doesn't do anything”. Commented Feb 7, 2014 at 17:22

6 Answers 6

11

You're adding all of the controls on top of each other, which is why it looks like there is only one of them. You'll want to put them in some sort of layout based control/panel (such as a FlowLayoutPanel) that will automatically place the structures in the appropriate location based on the type of layout that you want.

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

Comments

7

I just wrote a fast C# project in my visual studio. The code below adds a new textbox to the form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        TextBox txtBox;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtBox = new TextBox();
            txtBox.Location = new Point(10, 50);
            txtBox.Visible = true;
            Controls.Add(txtBox);
        }
    }
}

------------------------------------------ADDED-------------------------------------

The code below, will add 4 textboxes and 4 labels, like you want it. You can see the picture(at the end of the code), how it shows on my example.

P.s.: You will need to configure the position properly though.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        TextBox[] txtBox;
        Label[] lbl;

        int n = 4;
        int space = 20;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtBox = new TextBox[n];
            lbl = new Label[n];

            for (int i = 0; i < n; i++)
            {
                txtBox[i] = new TextBox();
                txtBox[i].Name = "n" + i;
                txtBox[i].Text = "n" + i;

                lbl[i] = new Label();
                lbl[i].Name = "n" + i;
                lbl[i].Text = "n" + i;
            }


            for (int i = 0; i < n; i++)
            {
                txtBox[i].Visible = true;
                lbl[i].Visible = true;
                txtBox[i].Location = new Point(40, 50 + space);
                lbl[i].Location = new Point(10, 50 + space);
                this.Controls.Add(txtBox[i]);
                this.Controls.Add(lbl[i]);
                space += 50;
            }

        }
    }
}

Screenshot: http://shrani.si/f/1F/Y/22BgTuBX/example.png

I also took the time and uploaded the project i made to Sendspace.

Download link: http://www.sendspace.com/file/glc7h2

6 Comments

But it doesn't add 4 textboxes and 4 labels. Try running the OP's code to see where his problem lies.
You are right. Therefore i made a new project containing the solution he is searching for. At least i hope this is the thing he is looking for! :)
You almost certainly don't want to be manually specifying the location. This results in forms that can't handle controls of a dynamic size (which is extraordinarily common), cannot be resized, etc. It's also a lot of work to try to align everything correctly, even when everything is static in its size. You almost certainly want to use some sort of layout manager instead.
The site is designed to create high quality answers, not any old answer. It is expected for users to indicate through voting and comments when an answer is not of high quality. It is not expected for users to ignore low quality answers. Your solution may answer the question, but it is not a very good answer, and it creates many new problems in the process. That is highly relevant, and posting a comment indicating that is entirely appropriate on this site. Given that you've been here for a day, and me 2 years, I'd say I have a somewhat better understanding of how the site works.
I really dont know who i got the answer downvoted. I posted a correct answer to his problem. It may not be the best, but it works as asked in the question. :(
|
1

Yes first define where you want to add the control in the page and add the control on that main control. Example page have one panel and it’s name is pnl1 so use like below

pnl1.Controls.Add(textBox[i]);
pnl1.Controls.Add(label[i]);

Comments

1

The Textboxes and Labels are placed on top of each other, since you didn't specify a location for them.

Change your code to:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

    namespace Sampless
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int n = 4;

        private void btnDisplay_Click(object sender, EventArgs e)
        {
            TextBox[] textBox = new TextBox[n];
            Label[] label = new Label[n];
            int labelX, labelY, textboxX, textboxY;

            labelX = 20;
            labelY = 20;
            textboxX = 50;
            textboxY = 20;

            for (int i = 0; i < n; i++)
            {
                textBox[i] = new TextBox();
                textBox[i].Name = "n" + i;
                textBox[i].Text = "n" + i;
                textBox[i].Location = new Point(textboxX, textboxY);

                label[i] = new Label();
                label[i].Name = "n" + i;
                label[i].Text = "n" + i;
                label[i].Location = new Point(labelX, labelY);

                labelY += 25;
                textboxY += 25;
            }

            for (int i = 0; i < n; i++)
            {
                this.Controls.Add(textBox[i]);
                this.Controls.Add(label[i]);
            }
        }
     }
}

Textboxes and Labels will be shown in 2 columns, adding 25 to their Y values every row.

3 Comments

You almost certainly don't want to be manually specifying the location. This results in forms that can't handle controls of a dynamic size (which is extraordinarily common), cannot be resized, etc. It's also a lot of work to try to align everything correctly, even when everything is static in its size. You almost certainly want to use some sort of layout manager instead.
@Servy I understand, but this is an answer to solve the specific question of the user, by showing him what went wrong. The next step would be correctly aligning the labels and textboxes, but that should be taking care of by himself.
This is an answer that creates many new problems in its attempt to solve the one proposed. It is an approach for solving the problem that I'm asserting shouldn't be used at all. The OP shouldn't have to go on his own spending a bunch of time trying to properly lay out the controls. he should use one of the layout panels designed to lay them out for him. That will be dramatically easier and much more effective. Such a solution in no way requires ever touching the Location properties.
0

The array creation call just initializes the elements to null. You need to individually create them. Try This

TextBox[] txtTeamNames = new TextBox[teams];
for (int i = 0; i < txtTeamNames.Length; i++) {
  var txt = new TextBox();
  txtTeamNames[i] = txt;
  txt.Name = name;
  txt.Text = name;
  txt.Location = new Point(172, 32 + (i * 28));
  txt.Visible = true;
}

1 Comment

You almost certainly don't want to be manually specifying the location. This results in forms that can't handle controls of a dynamic size (which is extraordinarily common), cannot be resized, etc. It's also a lot of work to try to align everything correctly, even when everything is static in its size. You almost certainly want to use some sort of layout manager instead.
0
namespace Sample
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        TextBox txbx = new TextBox();
        private void button1_Click(object sender, EventArgs e)
        {
            AddNewTextBox();

            txbx = new TextBox();

            txbx.Location = new Point(10, 20);

            txbx.Visible = true;

            Controls.Add(txbx);

        }

    }
}

1 Comment

This is also running ... Dynamically create a one new textbox control,,..

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.