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!
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)
{
...
}
}
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");
Try creating your constructor, but also creating a default parameterless constructor.
Take a look at this question
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.