Dynamics 365 Business Central: How to get all Enum Values (loop through all enum values) in AL

Dynamics 365 Business Central

Hi, Readers.
Today I would like to share another mini tip about Business Central, how to get all Enum Values (loop through all enum values) in AL.

An enumeration type, also known as an enum in programming, is a keyword used to declare a type that consists of a set of named constants. The list of named constants is called the enumeration list. Enums can be used as table fields, local and global variables, and parameters.

You can find all Enums in AL Explorer by grouping them by Type. More details: AL Explorer and AL Home in Visual Studio Code AL extension

For example, enum 37 “Sales Line Type”:

So can we get all the values ​​in enum 37 “Sales Line Type” at once? Or loop through all enum values? In .net, we can use the Enum.GetValues Method (System) (Retrieves an array of the values of the constants in a specified enumeration), but what about in AL?

In fact, this is not difficult. We just need to use Enum.Names() Method (Gets the value names). In fact, its return value is List of [Text].

Let’s look at a simple example:

Great. (Includes the extended values ​​in Enum Extension)

Test code:

pageextension 50100 CustomerListExt extends "Customer List"
{
    trigger OnOpenPage()
    var
        EnumValue: Text;
        AllEnumValues: Text;
    begin
        AllEnumValues := '';
        foreach EnumValue in Enum::"Sales Line Type".Names() do begin
            AllEnumValues += EnumValue + '\';
        end;
        if AllEnumValues <> '' then
            Message(AllEnumValues);
    end;
}

If you just need the id, you can also use Enum.Ordinals() Method. The method is the same. For example,

Finally, if you need to get the total number of values ​​in the Enum, using FieldRef.EnumValueCount() Method is the fastest. For example,

PS: Business Central 2023 wave 2 (BC23): Check if a field is an enum (New FieldRef.IsEnum method)

Very simple, give it a try!!!😁

END

Hope this will help.

Thanks for reading.

ZHU

コメント

Copied title and URL