Using the switch statement in a Windows Forms application - c#

And I'm doing some exercises about switch. I just did it from console application and I would like to do it in window forms applications. I'm looking for syntax on how to do switch in window forms.
In console it's usually like this:
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered numbered two");
break;
default:
break;
how can I do this in my window forms, if I would like to display this cases in listbox1?
Thanks
=======
Thank you. I tried this one but I'm getting an error. This is what I've tried:
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one");
break;
}
}
========
This is the code I'm trying to do:
private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
this.listBox1.Items.Add("You have entered numbered one");
break;
}
}
====
This is the new code:
private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
WriteNumber(intNumber);
}
else
{
MessageBox.Show("Please enter an integer not a character");
}
}
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listBox2.Items.Add("You have entered numbered one");
break;
case 2:
listBox2.Items.Add("You have entered numbered two");
break;
case 3:
listBox2.Items.Add("You have entered numbered three");
break;
default:
listBox2.Items.Add("You have exceeded the range of 1-3. Please enter the number between 1-3");
break;
}

The switch/case syntax is identical between WinForms and a console app (or any other type of application or class library), the only difference is how you display the data. If you want to add a string to a listbox (which is apparently what you're asking), it's as simple as
listBox1.Items.Add("Here is the text of the list box item");

This should work:
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one"); break;
}
}
You need to remove the static keyword to get access to the listbox, which is an instance variable.

This works fine:
switch (wordValue)
{
case 1:
this.listBox1.Items.Add("You have entered numbered two");
break;
default:
break;
}

Related

How to access first element (REQ) on enum by switch case statement?

I work on csharp i face issue i can't access element inside switch case statement as
case RoleNames.REQ:
so How to do that ?
I create enum as below :
public enum RoleNames
{
REQ,
HRED,
PLNG,
REC,
CEO
}
2- I call enum to get first element by switch case on Main function console .
static void Main(string[] args)
{
RoleNames rn=new RoleNames();
switch (rn)
{
case RoleNames.REQ:
break;
case RoleNames.HRED:
break;
case RoleNames.PLNG:
break;
case RoleNames.REC:
break;
case RoleNames.CEO:
break;
default:
break;
}
}
I need to access first element on switch as
RoleNames.REQ:
when debug code above switch go direct to default break
so what change i can do on my code to access first element case RoleNames.REQ:

How do I add a Y/N to Switch-Cases in C#?

I'm a complete Newbie to the world of programming, yet I really wish to learn a lot as quick as possible and now came up to a problem that I can't find to solute just via researching and "learning- by doing" (Trying around).
Basically I'm trying to work on a small console- based TextAdventure in C Sharp (With VisualStudios) Now I came to a Case- Switch (Offering the User some Options to read and walk through), but I wish to add a Y/N Confirmation in case the User decides to take a different path. For now it's only for the starting point of the story:
Does the User want to go into "The Wilds", "The City", "The Farm". Something as simple as that just in addition: "Are you sure (Y/N)?" leading the No to return the given choices.
Thank you all in advance and stay healthy!
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
private void TakeYourLeave()
{
WriteLine("\nYou are about to take your leave... Are you sure ? (Y/N)");
ReadKey();
Environment.Exit(0);
}
private void VisitTheMemorial()
{
Clear();
//FILLER//
WriteLine("You may proceed by the press of any button.");
ReadKey(true);
RunMainMenu();
}
private void EnterTheWorld()
{
string prompt = "Where would you like to start your journey?";
string[] options = { "The Slums", "The Wilds", "The City", "The Farm" };
Menu startMenu = new Menu(prompt, options);
int selectedIndex = startMenu.Run();
BackgroundColor = ConsoleColor.White;
switch (selectedIndex)
{
case 0:
ForegroundColor = ConsoleColor.Black;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 1:
ForegroundColor = ConsoleColor.Green;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 2:
ForegroundColor = ConsoleColor.Red;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 3:
ForegroundColor = ConsoleColor.Yellow;
WriteLine("\n ||Small Description|| Are you sure to take this path? (Y/N)");
break;
}
In this case, you need to take care of a few things:
Make sure that the entire switch-statement logic is in a while-loop, as such:
while (True) {
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
Check with your function if the input given is "No", if such, then immeditely return so your function exits before any navigation
private void VisitTheMemorial()
{
userInput = readKeyFunction();
if (userInput == "no") {
return;
}}
Finally, if the user doesn't select no, just do nothing and let the function go on
It is best to handle the 'Are you sure?' inside the menu.Run(), and return a value to the selectedIndex after the confirmation. Also avoid using while loop at the main flow in this case.
Note: you have to think in a modular way. Consider your Menu class as a module which handles user choice. The main flow does not have to bother about the confirmation by the user, it just have to process the final result of the user.
Another suggestion: Use enums instead of integers wherever possible for multiple choices.

C# adjustable hotkey funtion for press Buttons question

Im creating a Hotkey funtion atm so users can adjust Keybindings to their own needs, before i set the keys and they were not adjustable. This is what i used before.
public void gHook_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.D:
// stuff
Salvagebtn.PerformClick();
break;
case Keys.F12:
// stuff
pausebtn.PerformClick();
break;
case Keys.K:
//stuff
Geardropbtn.PerformClick();
break;
case Keys.F:
//stuff
Gamblebtn.PerformClick();
break;
case Keys.A:
//stuff
LeftClickSpambtn.PerformClick();
break;
case Keys.H:
// stuff
openGRbtn.PerformClick();
break;
case Keys.B:
//stuff
gemupbtn.PerformClick();
break;
}
}
Now i made a setting Tab where ppl can change Keybindings which looks like this.
How can i get it going that instead of the "case Keys.D:" it will react to the Keybinding in the Textbox ?
A few ways to do it. One way you could go would be to assign the keybindings to a Dictionary where UserActions is an enum defining the possible action:
public enum UserAction
{
Salvage, Pause, Drop // etc...
}
Then when the user presses a key, something like:
public void gHook_KeyDown(object sender, KeyEventArgs e)
{
string k = e.KeyCode.ToString();
if (KeyBindings.Contains(k)) //KeyBindings is your field or variable which is a Dictionary<string, UserAction>
{
var action = KeyBindings[k]
switch (action)
{
case UserAction.Salvage:
// stuff
Salvagebtn.PerformClick();
break;
case UserAction.Pause:
// stuff
pausebtn.PerformClick();
break;
// and so on...
Assigning values to the dictionary:
var KeyBindings = new Dictionary<string, UserAction>;
KeyBindings["D"] = UserAction.Salvage;
KeyBindings["A"] = UserAction.Pause;
If you need to get a key from the user's input, you can use Enum.TryParse(input):
Keys key;
if (Enum.TryParse<Keys>(textBoxSalvage.Text, out key))
{
KeyBinding[textBoxSalvage.Text] = UserAction.Salvage; // note that 'UserAction.something' comes from the context
}

Switch Statement C#

Can someone please tell me why my switch statement is not working? In my program I have a text box with the choices of 'Billing', 'Tech Support', 'Retention', 'Customer Service'. My switch statement is saying if that text box is = xxx then show a form I build and hide everything else.
Currently only the billing and other option works?!
<
private void cbDept_SelectedIndexChanged(object sender, EventArgs e)
{
string reason = cbDept.Text;
switch (reason)
{
case "Billing":
gbBilling.Show();
gbTechSupport.Hide();
gbCS.Hide();
gbRetention.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Tech Support":
gbTechSupport.Show();
gbBilling.Hide();
gbCS.Hide();
gbRetention.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Retention":
gbRetention.Show();
gbBilling.Hide();
gbTechSupport.Hide();
gbCS.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Customer Service":
gbCS.Show();
gbBilling.Hide();
gbTechSupport.Hide();
gbRetention.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Other":
txtOther.Show();
lbOtherReason.Show();
gbCS.Hide();
gbBilling.Hide();
gbTechSupport.Hide();
gbRetention.Hide();
break;
default:
gbCS.Hide();
gbBilling.Hide();
gbTechSupport.Hide();
gbRetention.Hide();
break;
}
}
>
It seems to me that there is some misspelling in the other options. Check the values of reason before reaching the switch.

switch and if in C#

Why does the following work (compile):
public void SaveCurrentTab(string currentTabIndex)
{
if (currentTabIndex == MainInfoPnl.ClientID)
PartialSave1();
else if (currentTabIndex == ContactInfoPnl.ClientID)
PartialSave2();
else if (currentTabIndex == BankInfoPnl.ClientID)
PartialSave3();
else if (currentTabIndex == ServicesPnl.ClientID)
PartialSave4();
else if (currentTabIndex == AttachmentsPnl.ClientID)
PartialSave5();
}
But, the following does not?
public void SaveCurrentTab(string currentTabIndex)
{
switch (currentTabIndex)
{
case MainInfoPnl.ClientID:
PartialSave1();
break;
case ContactInfoPnl.ClientID:
PartialSave2();
break;
case BankInfoPnl.ClientID:
PartialSave3();
break;
case ServicesPnl.ClientID:
PartialSave4();
break;
case AttachmentsPnl.ClientID:
PartialSave5();
break;
}
}
Presumably because MainInfoPnl.ClientID isn't a compile-time constant. It may be public static readonly for example, which isn't the same as const. If that doesn't help, show us more about the code and the error message you're getting.
The case statements must be constant strings for a switch - an if condition has no such restriction.
A switch in C# only works with constant values. For values determined at runtime, use a if-else construction.
Try this:
public void SaveCurrentTab(string currentTabIndex)
{
switch (Convert.ToInt32(currentTabIndex))
{
case (int)MainInfoPnl.ClientID:
PartialSave1();
break;
case (int)ContactInfoPnl.ClientID:
PartialSave2();
break;
case (int)BankInfoPnl.ClientID:
PartialSave3();
break;
case (int)ServicesPnl.ClientID:
PartialSave4();
break;
case (int)AttachmentsPnl.ClientID:
PartialSave5();
break;
}
}

Categories

Resources