Ilja
Ilja

Reputation: 46479

Listen for a tab click in tab control

I'm struggling to figure out how to know when user clicks a certain tab button in windows form application.

At the moment I have following set up (Form1.Designer.cs):

//Adding click event handler to desired tab
this.tabStartPageView.Click += new System.EventHandler(this.tabStartPageView_Click);

And in my Form1.cs file:

private void tabStartPageView_Click(object sender, EventArgs e)
{
    Console.WriteLine("Click Tested");
}

But nothing happens when I click on a tab, console only writes "Click Tested" when I click within window area associated to the tab.

EDIT: The reason I need to know this is so I can get data from an xml file on tab click and dynamically build its view depending on it.

I have tried:

if(tabControlViews.SelectedTab == tabStartPageView)
{
    //do something
}

But I get error saying: [APP NAME] is a 'field' but is used like a 'type' ...\Form1.cs

Upvotes: 0

Views: 3804

Answers (2)

wakthar
wakthar

Reputation: 718

Handle TabControl SelectedIndexChanged event as follows:

 private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (tabControl1.SelectedTab == tabControl1.TabPages["tabPage1"])
     {
         MessageBox.Show("tabPage1");
     }
     // And so on....
 }

Upvotes: 0

Delta
Delta

Reputation: 161

Implement it as below suggetion in Form Constructor

public Form1() {
  InitializeComponent();    
  Tabs.SelectedIndexChanged += new EventHandler(Tabs_SelectedIndexChanged);
}

and than implement it

void Tabs_Selected(object sender, TabControlEventArgs e) {
  if (e.TabPage == TaskListPage) {

  }
}

Upvotes: 2

Related Questions