Windows窗体事件“在选择选项卡上”?
我正在用C#构建一个Windows窗体应用程序。 如何选择选项卡菜单上的某个选项卡时,如何触发代码?
我认为这是TabControl.SelectedIndexChanged
事件。
只需看看MSDN。 我从那里拿走了它。 假设您将选项卡控件tabControl1
命名为。 您需要使用以下方式订阅此活动:
tabContrl1.TabControl.SelectedIndexChanged += tabControl1_SelectedIndexChanged;
并添加事件处理程序
private void tabControl1_SelectedIndexChanged(Object sender, EventArgs e) { MessageBox.Show("You are in the TabControl.SelectedIndexChanged event."); }
TabControl
及其SelectedIndexChanged
事件将满足您的需求。
例如,您在表单的详细信息部分中有一个带有TabControl
的Customer文件。 当用户单击Transactions TabPage
时,您希望加载延迟加载此客户的事务。 您的代码应该看起来像这个伪代码:
public partial class CustomerMgmtForm : Form { // Assuming the design already done, so the TabControl control exists on your form. public CustomerMgmtForm() { tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged); } private void tabControl1_SelectedIndexchanged(object sender, EventArgs e) { switch((sender as TabControl).SelectedIndex) { case 0: // Do nothing here (let's suppose that TabPage index 0 is the address information which is already loaded. break; case 1: // Let's suppose TabPage index 1 is the one for the transactions. // Assuming you have put a DataGridView control so that the transactions can be listed. // currentCustomer.Id can be obtained through the CurrencyManager of your BindingSource object used to data bind your data to your Windows form controls. dataGridview1.DataSource = GetTransactions(currentCustomer.Id); break; } } }
使用TabControl
时,以下内容也很有用。
- TabControl.TabPages.Add();
- TabControl.TabPages.Contains();
- TabControl.TabPages.ContainsKey();
- TabControl.TabPages.Insert();
- TabControl.TabPages.Remove();
- TabControl.TabPages.RemoveAt();
- TabControl.TabPages.RemoveByKey()。
使用TabControl.TabPageCollection Members
。
编辑#1
要选择特定选项卡,它只能用0,1,2标识,而不能用标签名称标识?
是的,您也可以增加或减少TabControl.SelectedIndex
属性以使特定的TabPage
选择/激活。
但有一点,请确保不要将TabPage
从TabPages.Count - 1
索引,因为起始索引为0,否则将引发IndexOutOfRangeException
抛出。
继续我们有两个页面的示例,地址信息和交易:
// Will automatically change the selected tab to the Transactions TabPage. tabControl1.SelectedIndex = 1; // Considering there a count of two TabPages, the first is indexed at 0, and the second at 1. // Setting the SelectedIndex property to 2 will throw. tabControl1.SelectedIndex = 2;
注意:对TabControl.SelectedIndex
属性的任何更改都将触发TabControl.SelectedIndexChanged
事件。
要选择特定选项卡,是否只能通过0,1,2标识,而不是选项卡名称?
您可以通过将事件侦听器添加到实际选项卡而不是选项卡控件来执行此操作。
如果您有一个名为tabHistory的选项卡,则可以在设计器中添加以下行。
this.tabHistory.Enter += new System.EventHandler(this.tabHistory_Enter);
然后只需添加您的方法来捕获事件。
private void tabHistory_Enter(object sender, EventArgs e) { MessageBox.Show("Hey! Ive got focus"); }
如果你有例如3个标签……
if (tabControl.SelectedTab == tabControl.TabPages[0]) do something... if (tabControl.SelectedTab == tabControl.TabPages[1]) do something else... if (tabControl.SelectedTab == tabControl.TabPages[2]) do something else...
检查这是否对您有所帮助 。 “ SelectedIndexChanged
”可能对您有所帮助。
MSDN的详细信息在这里