C# TabControl TabPage passing events

2019-08-25 08:59发布

I am working with a TabControl and attaching TabPages to the TabControl, but am having a problem making one of the TabPages respond to an event. It makes me think that I am missing something about the relationship between these classes, so would appreciate some help. I want to add a number of TabPage objects to TabControl, and for one of them (the first one added), I want to send it an event to make it do something.

Here is the basic code:

/* tabControl is a TabControl object, and 
tabNames is a string array */

bool first = true;
foreach (string tabName in tabNames)
{
    TabPage tabPage = CreateTabPage(tabName);
    tabControl.Controls.Add(tabPage);
    if (first)
    {
        methodTabPage.Select();
        first = false;
    }
}

private TabPage CreateTabPage(String name)
{
    TabPage tabPage = new TabPage(name);
    tabPage.Enter += new EventHandler(MethodTab_Entered);
    return tabPage;
}

private void MethodTab_Entered(object sender, EventArgs e)
{
    DoSomething();
}

When I run this code, as far as I can tell, DoSomething() never gets called. I have tried various things such as the Click event, and so on, but cannot get this to work as expected. What am I missing?

Thanks, Martin

1条回答
Bombasti
2楼-- · 2019-08-25 09:29

This here works fine for me:

public partial class TabPageForm : Form
{
    private List<string> tabNames;
    public TabPageForm()
    {
        InitializeComponent();

        tabNames = new List<string>();
        tabNames.Add("NewTab");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bool first = true;
        foreach (string tabName in tabNames)
        {
            TabPage tabPage = CreateTabPage(tabName);
            methodTabPage.Controls.Add(tabPage);
            if (first)
            {
                methodTabPage.Select();
                first = false;
            }
        }
    }

    private TabPage CreateTabPage(String name)
    {
        TabPage tabPage = new TabPage(name);
        tabPage.Enter += new EventHandler(MethodTab_Entered);
        return tabPage;
    }

    private void MethodTab_Entered(object sender, EventArgs e)
    {
        DoSomething();
    }

    private void DoSomething()
    {
        throw new NotImplementedException();
    }
}

DoSomething is called when I enter the newly created tab.

Of course, the logic of the first variable is probably not as you intend it to be, so if you could clarify the semantics of it, I could update my code snippet.

Cheers

查看更多
登录 后发表回答