0

In C# win forms- I would like to add controls to form from other class.

How can I do it?

I tried to pass the form as formal parameter to function in the other class, but how can I attach it to the form?

class Class1 { System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox(); } 

In addition, I have Form1.cs

I would like to add txt to Form1.

In addition, I would like to set the properties of txt from Class1, and it failed..

Thanks!

1
  • You can easily add a method that returns a new TextBox instance. You however have next-to-no shot at getting it in the right location or giving it the right tab index. UI is the top dog, your form can use your class easily. Having your class use the form, that's trouble. Don't do it. Commented Mar 20, 2016 at 16:46

1 Answer 1

1

This should work:

class Class1 { System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox(); public void AddTextBoxToForm(Form form) { form.Controls.Add(txt); txt.Text = "Hello World! I've been added to a form."; } } 

You may also set properties like Location and Size of the TextBox. Note that it will be a bad idea to add the TextBox to different forms, though.

If you have any errors, your question should be more specific about what "failed" means.


In general, all controls of a Form should rather be members of that Form and not be defined in other classes.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.