Reputation: 5873
I have a enumerator that holds tabpage collection names. I would like to use tabControl.SelectedIndexChanged
event to execute specific code based on the caption/name of the tabpage.
Is it possible to use a switch statement like:
private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
{
var tc = (TabControl)sender;
switch (tc.SelectedTab.Name)
{
case Enum.GetName(typeof(tabPages), 0):
// This is table page 0 , name="interchanges"
// set default values
break;
case Enum.GetName(typeof(tabPages), 1):
// Do something else page=1,name="ShowContents"
break;
}
}
Upvotes: 2
Views: 184
Reputation: 12075
Alternative suggestion, although possibly harder to maintain:
Attach a delegate to the 'Tag' of each page, and have your code simply invoke whichever delegate is on that page. Your code becomes:
var tc = (TabControl)sender;
Action action = tc.Tag as Action;
if (action != null)
action();
Another possibility is having a static Dictionary<string, Action> myActions
defined, and just calling
myActions[tabName]();
Upvotes: 0
Reputation: 1010
You should convert the string to the enum. And then switch this. Example:
tabPages tab = (tabPages)Enum.Parse(typeof(tabPages),tc.SelectedTab.Name);
switch (tab)
{
case tabPages.interchanges:
// This is table page 0 , name="interchanges"
// set default values
break;
case tabPages.Showcontents:
// Do something else page=1,name="ShowContents"
break;
}
Edit: Made this example real quick:
using System;
public class Test
{
public static void Main()
{
string text = "One";
TestEnum test = (TestEnum)Enum.Parse(typeof(TestEnum), text);
switch (test)
{
case TestEnum.One:
Console.WriteLine("ONE!");
break;
case TestEnum.Two:
Console.WriteLine("TWO!");
break;
case TestEnum.Three:
Console.WriteLine("THREE!");
break;
}
}
public enum TestEnum
{
One,
Two,
Three
}
}
Upvotes: 2