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!

john
  • 4,043
  • 7
  • 27
  • 39
  • 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? – sll Nov 07 '11 at 15:37
  • Can you elaborate on what "some information" is? – Robert Harvey Nov 07 '11 at 15:38

3 Answers3

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)
   {
      ...
   }
}
KeithS
  • 70,210
  • 21
  • 112
  • 164
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");
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
0

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

Take a look at this question

Community
  • 1
  • 1
Richard Friend
  • 15,800
  • 1
  • 42
  • 60