C#TabControl.SelectedIndex意外更改值

时间:2017-10-13 08:12:54

标签: c# winforms tabcontrol

我有一个名为OpenURL()recordHistory()的方法,其定义如下:

public string OpenURL(string url)
{
       //get index of current tab
       int tabIndex = BrowserWindow.TabControlE.SelectedIndex;
       //create instance of History class
       History H = new History();
       //call recordHistory() method to record the url and tabIndex
       H.recordHistory(url, tabIndex);
}

public void recordHistory(string url, int tabIndex)
{
       //print the tabIndex
       Console.WriteLine("Tab is: "+tabIndex);
}

场景是:我想记录每个标签的历史记录。 但是,我面临来自TabControl.SelectedIndex的一些意外行为。

创建第一个标签时,recordHistory()中的输出为:

Tab is: -1

当我刷新页面时(在同一个标​​签上调用OpenURL()),这次recordHistory()的输出是:

Tab is: 0

似乎第一次创建选项卡时TabControl.SelectedIndex值是错误的。刷新页面后会消失。如何更正此值以显示正确的值?

编辑:添加recordHistory()来电。

在课程BrowserWindow中:

private void BrowserWindow_Load(object sender, EventArgs e)
{
    TabControl1 = new TabControl();
    TabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
    Tab Tab1 = new Tab(tab_counter, getHomePageURL());
    TabControl1.Controls.Add(Tab1.createNewTab());
    this.Controls.Add(TabControl1);
}

在课程Tab中:

class Tab
{
    int tab_ID;
    String tab_URL;
    TabPage page;

    public Tab(int tab_ID, String tab_URL)
    {
        this.tab_ID = tab_ID;
        this.tab_URL = tab_URL;
    }

    public TabPage createNewTab()
    {
        //Create a new tab
        page = new TabPage("New Tab");
        page.Text = this.tab_URLE;
        page.Controls.Add(R1);
        R1.Text = OpenURL(this.tab_URLE);
        return page;
    }

 }

流程:BrowserWindow_Load() --> createNewTab() --> OpenURL() --> recordHistory()

1 个答案:

答案 0 :(得分:0)

问题在于您的BrowserWindow_Load事件。更改最后2个语句的顺序,它应该工作。像这样:

private void BrowserWindow_Load(object sender, EventArgs e)
{
    TabControl1 = new TabControl();
    TabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
    Tab Tab1 = new Tab(tab_counter, getHomePageURL());
    this.Controls.Add(TabControl1);
    TabControl1.Controls.Add(Tab1.createNewTab());
}