C# TabControl TabPage passing events

风格不统一 提交于 2019-12-25 02:59:10

问题


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:


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



来源:https://stackoverflow.com/questions/33249427/c-sharp-tabcontrol-tabpage-passing-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!