7

找到打开哪个选项卡的最简单方法是什么。当我单击 tabpage2 或其他一些标签页时,我想显示一些数据。我这样做了,但不是很好的解决方案:

private int findTabPage { get; set; }
    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (tabControl1.SelectedTab == tabPage1)
            findTabPage = 1;
        if (tabControl1.SelectedTab == tabPage2)
            findTabPage = 2;
    }

并用于显示数据:

 if (findTabPage == 1)
     { some code here }
 if (findTabPage == 2)
     { some code here }

有没有像这样的其他解决方案?

4

4 回答 4

14

采用

tabControl1.SelectedIndex;

这将为您提供选定的选项卡索引,该索引将从 0 开始,直到 1 小于您的选项卡总数

像这样使用它

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch(tabControl1.SelectedIndex)
    {
        case 0:
             { some code here }
             break;
        case 1:
             { some code here }
             break;
    }
}
于 2012-05-10T06:58:07.877 回答
4

这是一个更好的方法。

private int CurrentTabPage { get; set; }
    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        CurrentTabPage = tabControl1.SelectedIndex;
    }

这样每次 tabindex 改变时,我们需要的 CurrentTabPage 就会自动更新。

于 2016-09-19T10:15:43.383 回答
3

只需使用tabControl1.SelectedIndex

if (tabControl1.SelectedIndex == 0)
    { some code here }
if (tabControl1.SelectedIndex == 1)
    { some code here }
于 2012-05-10T06:55:14.077 回答
3

如果您更喜欢获取一个字符串来标识选定的 tabPage 而不是它的索引:

int currentTab = tabControl1.SelectedIndex;
string tabText = tabControl1.TabPages[currentTab].Text;

这将给出您在选择 tabPage 时单击的文本。

int currentTab = tabControl1.SelectedIndex;
string tabName = tabControl1.TabPages[currentTab].Name;

这将为您提供 tabPage 的名称。

您可以通过编程方式或在对象属性中选择名称,必须使用不同的名称来标识每个 tabPage。相反,文本字段不是,几个不同的选项卡可以有相同的文本,你必须小心。

于 2021-03-15T22:50:22.437 回答