2

I have created a forms application which uses a TabControl. For each tab I want to place a single UserControl (created in the same project) which contains all the other controls. However, I will need to pass some information from the primary form to the UserControl for it to work property with events, methods, etc. How can/should I do this?

I tried creating a constructor with parameters but then Designer fails and I have to go in and delete out the added UserControl references.

Thanks!

2
  • Constructor parameter is a right way. (also it make sense to abstract custom object parameters by interfaces to simplify testing) Could you provide a code after adding which a designer start complaining? Commented Nov 7, 2011 at 15:37
  • Can you elaborate on what "some information" is? Commented Nov 7, 2011 at 15:38

3 Answers 3

0

The constructor parameter is the correct method. However, there must still be a default constructor in order for the Designer to be able to construct (and draw) a copy of the object.

My usual workaround is to put a clause in the default constructor, checking to see that we are in "design mode" and throwing an exception if not:

public class MyForm: Form
{
   public MyForm()
   {
      if(!DesignMode) throw new InvalidOperationException("Cannot use default constructor in production code");
   }

   public MyForm(MyDependency dependent)
   {
      ...
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can pass information by a function that created in usercontrol.cs file.

for example in usercontrol.cs

public string name;
public void SetName(string pname)
{
this.name = pname;
} 

or maybe you want to change button name

Button mybutton = new Button();
public void SetButtonName(string btname)
{
this.mybutton.Text = btname;
}

Now you can call these functions in your mainform.cs

Myusercontrol usc = new Myusercontrol();
usc.SetName("this is string for 'name' string");
usc.SetButtonName("this is string for button text");

Comments

0

Try creating your constructor, but also creating a default parameterless constructor.

Take a look at this question

Comments

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.