f1
is null because no form has been assigned to it. Drop this property and instead write:
TabPage tp = new TabPage { };
tp.Text = "NewTab";
tp.Controls.Add(new b());
FindForm().Controls.OfType<TabControl>().Single().TabPages.Add(tp);
This assumes that the form contains exactly one TabControl and that it is a top level control. If it can be inside another container control, you will have to loop the controls recursively. This question might help: Loop through all controls on a form, even those in groupboxes
Note, that your approach has yet another issue: f1
is typed as Form
, but this general type has no tabControl1
. You would have to type it with a specific form type MyForm f { get; set; }
.
Maybe an easier way to access the TabControl is to let the form implement an interface defining just a property returning this TabControl:
public interface ITabControlProvider
{
TabControl MainTabControl { get; }
}
Then let your form implement it
public partial class MyForm : Form, ITabControlProvider
{
...
TabControl MainTabControl { get { return tabControl1; } }
}
Now your UserControl can find the TabControl like this
var frm = FindForm() as ITabControlProvider;
if (frm != null) {
frm.MainTabControl.TabPages.Add(tp);
}