The Switch function in PowerApps evaluates a formula against a list of values and returns a result that corresponds to the first matching value. It is useful for simplifying complex conditional logic by providing a more readable and maintainable way to handle multiple possible values.
PowerApps – Switch() function Syntax
Switch(Formula, Match1, Result1 [, Match2, Result2, ... [, DefaultResult]])
- Formula: The expression to evaluate.
- Match1, Match2, ...: Values to compare against the result of the formula.
- Result1, Result2, ...: Results to return if the corresponding match is found.
- DefaultResult: (Optional) The result to return if no matches are found.
Notes:
- Default Result: Always include a default result to handle unexpected values and avoid potential errors.
- Case Sensitivity: Switch is case-sensitive. Ensure the match values have the correct case or handle case differences using functions like Lower or Upper.
PowerApps – Basic usage of Switch() function
Suppose you have a text input control named TextInput1, and you want to display a different message based on its value:
Switch(
TextInput1.Text,
"Hello", "Hi there!",
"Goodbye", "See you later!",
"Thanks", "You're welcome!",
"I don't understand"
)
This returns:
- "Hi there!" if TextInput1.Text is "Hello"
- "See you later!" if TextInput1.Text is "Goodbye"
- "You're welcome!" if TextInput1.Text is "Thanks"
- "I don't understand" if none of the above matches are found.
PowerApps – Basic usage of Switch() function in Numeric values
Suppose you have a dropdown control named Dropdown1 with numerical values, and you want to display corresponding text for each value:
Switch(
Dropdown1.Selected.Value,
1, "One",
2, "Two",
3, "Three",
"Other"
)
This returns:
- "One" if the selected value is 1
- "Two" if the selected value is 2
- "Three" if the selected value is 3
- "Other" if none of the above matches are found.
PowerApps - Display labels based on different status value
Suppose you have a status field in a form and you want to display different messages based on the status value:
Switch(
Status,
"Pending", "Your request is pending approval.",
"Approved", "Your request has been approved.",
"Rejected", "Your request has been rejected.",
"Unknown status"
)
PowerApps – Set Control Properties using Switch function
You can use Switch to set properties of controls dynamically. For example, changing the fill color of a button based on its state:
Switch(
ButtonState,
"Normal", Color.Blue,
"Hover", Color.LightBlue,
"Pressed", Color.DarkBlue,
Color.Gray
)
PowerApps – Navigate Based on User Role
Suppose you have different screens for different user roles, and you want to navigate to the appropriate screen based on the user's role:
Switch(
UserRole,
"Admin", Navigate(AdminScreen, ScreenTransition.Fade),
"User", Navigate(UserScreen, ScreenTransition.Fade),
"Guest", Navigate(GuestScreen, ScreenTransition.Fade),
Notify("Unknown role", NotificationType.Error)
)
scriptend