سؤال

I need to somehow pass my tabControl to my user control, so I can access it from within user control.

User control has a button on click of which I want to change a tab index to different one. When I try to access tabControl from my user control it simply can't find it.

هل كانت مفيدة؟

المحلول

You could create a method in the user control that will take an instance of a TabControl to otherwise manipulate like this:

public partial class MyUserControl : UserControl{
    private TabControl _tabControl;

    public MyUserControl() {
        InitializeComponent();
    }

    public void AssignTabControl(TabControl tabControl) {
        _tabControl = tabControl;
    }

    private void buttonNextTab_Click(object sender, EventArgs e) {
        // this is merely an example.
        _tabControl.SelectedIndex += 1;
    }
}

And now, assuming that you have already added both the user control and the tab control to the containing form, you can supply the tab control instance to otherwise manipulate from the form's constructor like this:

public partial class MainForm : Form  {
    public MainForm() {
        InitializeComponent();
        myUserControl1.AssignTabControl(tabControl1);
    }
}

The benefit here opposed to simply supplying the tab control instance via a constructor is that you can retain designer support. The drawback however, is that you will be subject to an exception if you don't assign the tab control instance.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top