How To Use C# (C Sharp) Switch Case, Switch Case Samples

After you read this article, you will be able to use the 'Switch Case' Function on your C# Projects. This function becomes so handy with DropDownList & RadioButtonList !
16 April 2010
1 minutes read

Related Posts

C# Switch Case function is the same with Select Case function in Visual Basic. It is usually used along with DropDownLists or RadioButtonLists. We wiil demostrate a function here with s dropdownlist.

Switch Case function enables us to run what we need to run in a case that we want. After the demonstration, you will exactly see what it means !

Code Sample


 

1- Firstly, put the below code into the body section of your page;

 













2- And then, As you can see, we appointed 'DropDownList1_SelectedIndexChanged' to run on DropDownList's SelectedIndexChanged. So on our code page we will use the below code;


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) {
          switch(DropDownList1.SelectedValue) {

                  case "1":
                          Label1.Text = "DropDownList Value = 1";
                          break;
                  case "2":
                          Label1.Text = "DropDownList Value = 2";
                          break;
                  default:
                          Label1.Text = "None Of Them";
                          break;
          }

  } 




That's It ! Of course, we can give so many examples on switch case function but this is pretty much it is !

On our example when we select the item which has the value '1' on our dropdownlist, Label1's Text will be "DropDownList Value = 1" and on value '2' it will be "DropDownList Value = 2"

As you can see we added the below code at the end of our switch case function;

                  default:
                          Label1.Text = "None Of Them";
                          break;

It reffers that when an item which is not indicated as a case is selected, the fuction will run this value !

I hope it gives you an idea on C# (C Sharp) Switch Case Function !

 

Update on 2010-12-01 12:53:57

In order to use switch case with Enum type in C#, follow the following instructions;

 

    public enum MyEnum {

        enum1 = 1,
        enum2 = 2,
        enum3 = 3

    }

        public static string EnumSwitchCaseTry(MyEnum myenum) {

            switch (myenum) 
            {
                case MyEnum.enum1:
                    //Do whatever you need to do

                case MyEnum.enum2:
                    //Do whatever you need to do

                case MyEnum.enum3:
                    //Do whatever you need to do

                default:
                    break;
            }

            //.....

            //.....

        }