Reputation: 1397
What is the easyest way to find which tab is on. I want to show some data when i click on tabpage2 or some other tabpage. I did it like this but is not good solution:
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;
}
and for displaying data:
if (findTabPage == 1)
{ some code here }
if (findTabPage == 2)
{ some code here }
Is there any other solution for example like this?
Upvotes: 9
Views: 45078
Reputation: 577
If you prefer getting a string to identify the selected tabPage instead of its index:
int currentTab = tabControl1.SelectedIndex;
string tabText = tabControl1.TabPages[currentTab].Text;
That will give the text on which you click when selecting the tabPage.
int currentTab = tabControl1.SelectedIndex;
string tabName = tabControl1.TabPages[currentTab].Name;
And that will give you the name of the tabPage.
You can chose the Name programmatically or in the object properties, it's mandatory to have one different to identify each tabPage. On the contrary, the Text field is not, and several different tabs can have the same text, you have to be careful with that.
Upvotes: 4
Reputation: 409
This is a much better approach.
private int CurrentTabPage { get; set; }
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
CurrentTabPage = tabControl1.SelectedIndex;
}
In this way every time the tabindex is changed, our required CurrentTabPage would automatically updated.
Upvotes: 4
Reputation: 48558
Use
tabControl1.SelectedIndex;
This will give you selected tab index which will start from 0 and go till 1 less then the total count of your tabs
Use it like this
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
switch(tabControl1.SelectedIndex)
{
case 0:
{ some code here }
break;
case 1:
{ some code here }
break;
}
}
Upvotes: 16
Reputation: 174289
Simply use tabControl1.SelectedIndex
:
if (tabControl1.SelectedIndex == 0)
{ some code here }
if (tabControl1.SelectedIndex == 1)
{ some code here }
Upvotes: 3