Hi.
I used this code, to create a label while the program was running when I pressed the button

int i=0;
private void NakupRyby_Click(object sender, EventArgs e)
        {
            Ryby[i] = new System.Windows.Forms.Label();
            Ryby[i].Text = "<°])))>(";
            Ryby[i].Size = new System.Drawing.Size(38, 13);
            Ryby[i].Location = new System.Drawing.Point((10 * i) + 100, (10 * i) + 100);
            Controls.AddRange(new System.Windows.Forms.Control[] { Ryby[i] });
            i++;
        }

Then I had to move this code to class, which should do the same, but i can't really add the label to form's Controls from the class. I need to figure out, how to put the label into the form controls from the class while program running

Pass the control as a parameter when you call the function in the class, then return the control after you changed whatever properties you want to change. Something like Ruby1=class1.Myfunction(Ruby1). The function would look like: public static label MyFunction(label NewRuby1) and return NewRuby1; I know that there are other ways but this seems to be the easiest.

I kinda don't know how to apply your solution into my code. I created the function in the class correctly, but now I don't know how to modify Ruby1=class1.Myfunction(Ruby1) to make it run.. Ruby1 is a label, but that means I have to create one, or in my case 100 labels in the form, what I don't want to. I just want to create and specify a new label when I click the button.

I'm not in front of VS right now but you should be able to pass the form to the other class, add your label, then return the form back. Something like Form1=class1.myfunction(Form1); Then your function would be public static form MyFunction(form NewForm1).

Try the following code by pasting it in the Class. include System.Windows.Forms in class file

        public void InsertLabel(MainForm form)
        {
            Label labelControl = new Label();
            //Set the text
            labelControl.Text = "New Label";
            //Set the location of the label
            labelControl.Top = 100;
            labelControl.Left = 100;
            labelControl.Visible = true;
            form.Controls.Add(labelControl);
        }

Use the following code in form

        private void button1_Click(object sender, EventArgs e)
        {
            //Name of the class - ControlCreator
            ControlCreator clasObj = new ControlCreator();
            clasObj.InsertLabel(this);
        }
This article has been dead for over six months. Start a new discussion instead.