Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 7. Selection Components

The six components in Chapter 6 are all “fill in freely”: you type whatever text you like, enter whatever number you like. This chapter switches to a different kind, picking from a given set of options. The user doesn’t have to think about the format and can’t enter an unexpected value.

The workbench adds a third module, Filter. It takes a list of “Tag Content” entries, filters them by tag, then sorts them in some order, keeps only the first few, shows only a few columns, and deduplicates by content. Each of the four selection components is used once, which ties together everything this chapter covers.

The four components pass different parameter types to the handler function. For the same “one item selected”, single-select gives a string, the toggle gives a bool, and the two multi-selects give a group of object; for the same “nothing selected”, the four components also behave differently. Figure 7-1 is the comparison table.

Figure 7-1 The parameter types the four components pass back to the handler function

The following sections take them one by one. Here is what the module looks like when it first opens.

Figure 7-2 The Filter module, tags empty, sort and count already have default values

The “Tag” cell is empty, “Sort” already reads “Source text”, and “Count” already has “All” selected. The first is the automatically selected first item; the second is a value the sample gives explicitly. The two defaults come from different places, and 7.7 explains the difference.

7.1 Dropdown: Single-Select and Multi-Select

Dropdown has one switch, multiselect. Leave it out and it is single-select; write true and it is multi-select.

        var tags = gr.Dropdown(label: "Tag", choices: TaskFilter.AllTags.Select(tag => new Choice(tag)).ToArray(),
            multiselect: true, allowCustomValue: true, maxChoices: 3, numChoicesShown: 6, interactive: true);
        var sort = gr.Dropdown(label: "Sort", choices: new[] { new Choice("Source text"), new Choice("By tag"), new Choice("By length") }, interactive: true);

These two lines are two uses of the same component. tags is multi-select and can pick several tags at once; sort is single-select and can have only one sort order.

What is selected also looks different in the UI. A single-select dropdown shows the selected item right in the box, and the box stays one line; a multi-select dropdown turns each item into a small chip (the “To-do ×” in Figure 7-3), and the box grows taller as you add options. This is the same component looking different in its two modes, not two components.

The small-chip design has a side effect. Select a lot and the box keeps growing, pushing the content below down. So a multi-select dropdown is a poor fit for cases where “someone might pick dozens”. For that you want a CheckboxGroup with scrolling, or you simply shouldn’t make people pick one by one. That is half the reason the sample sets the limit to three.

Figure 7-3 Two tags selected, sorted by length, first three kept

In Figure 7-3 you can see the division of labor among this chapter’s four components: tags are two small chips (multi-select dropdown), sort is one line of text (single-select dropdown), count is three dots (radio buttons), and “Which columns to show” is three boxes plus a half-selected select-all box (checkbox group). The two cells on the right are the result and the summary.

The multi-select list doesn’t collapse after you pick one item. You can click several in a row; it closes only when you click outside the box. Each selected item shows as a small chip with a × on its right; click that to remove the item.

When to Use Multi-Select

Single-select and multi-select decide semantics, not just “can you pick more than one”.

Single-select suits “you must pick one of these, and only one”: sort order, unit, status. The user has only one answer in mind; multi-select would just make them hesitate.

Multi-select suits “you can pick zero, one, or several”: tags, columns to show, steps to run. Its empty state is meaningful. “Pick none” often means “no restriction” or “do nothing at all”, and neither of those meanings has a place in single-select.

That is why “Sort” is single-select and “Tag” is multi-select in the sample. There can be only one sort order, while several tags can apply at once.

Where the Options Come From

choices is a Choice list, so it can be built from anything: literals written in code, a static array in the business library, records read from a file or database. The sample uses both. Tags come from TaskFilter.AllTags in the business library; sort is hard-coded in the UI.

The order of the options is the order they are shown, and also the order of the indices in type: "index". To sort alphabetically, sort them before passing them in; to put “the common ones first”, do the same. The component doesn’t sort for you; it draws them in the order you give.

What happens if options repeat? Two Choices with the same value but different labels produce two rows in the dropdown that look different but return the same value when selected. Whichever the user picks, the result is the same, which looks like a bug. Deduplicate before passing them in, or make sure the values are unique.

(string, string) Filter(
    string items,
    object[] tags,
    string sort,
    string count,
    object[] columns,
    bool dedupe)

This is the signature of the filter step in the sample. Six parameters for six inputs; the second and the fifth are both object[]. Tags are a multi-select dropdown, “Which columns to show” is a checkbox group, and the two multi-selects give the same kind of container. 7.5 expands on the other ways this container can be declared.

The tags and columns parameters can’t be passed straight into the business layer. They are containers of object, and the business layer wants strings, so the handler function converts them first.

    var options = new FilterOptions(
        tags.Select(tag => tag?.ToString() ?? "").Where(tag => tag.Length > 0).ToArray(),
        sort,
        count,
        columns.Select(column => column?.ToString() ?? "").ToArray(),
        dedupe);

The question mark in tag?.ToString() ?? "" is necessary. The container’s element type is object, so in theory it could be null. Where(tag => tag.Length > 0) also drops empty strings along the way. If a user defines an empty value, it shouldn’t be treated as a tag.

The Whole Path from Control to Business Logic

Walk through these six parameters and you can see the boundary between the UI and the business logic.

  1. In the UI the user picks tags, chooses a sort order, sets the count, checks columns, and toggles dedupe;
  2. They click “Filter”, and the framework stuffs the six components’ values into Filter’s six parameters in order;
  3. Filter converts the six values to strings (object → string) and packs them into a FilterOptions;
  4. TaskFilter.Run in the business library takes those options and the list of entries and computes the result;
  5. Filter joins the result into two pieces of text and returns them to the two output components.

Step 3 is new in this chapter. In earlier chapters, components passed the handler function exactly the types the business layer wanted (string, double, bool); this chapter adds an intermediate state of “a container holding object” that has to be converted at the UI layer. Once it is in FilterOptions, the business side sees a clean array of strings and has no idea whether the UI used a dropdown or a checkbox group. This boundary is the one from Chapter 3, just with one more conversion.

Step 4 lives in core and is all the business rules of this module.

    public static FilterResult Run(IEnumerable<string> source, FilterOptions options)
    {
        var rows = source
            .Select(line => line.Trim())
            .Where(line => line.Length > 0)
            .Select(Parse)
            .ToList();

        var total = rows.Count;

        if (options.Tags.Count > 0)
        {
            rows = rows.Where(row => options.Tags.Contains(row.Tag)).ToList();
        }

        if (options.Dedupe)
        {
            rows = rows.DistinctBy(row => row.Text).ToList();
        }

        rows = options.Sort switch
        {
            "By tag" => rows.OrderBy(row => row.Tag, StringComparer.Ordinal).ToList(),
            "By length" => rows.OrderBy(row => row.Text.Length).ToList(),
            _ => rows,
        };

        var limit = options.Count switch
        {
            "First three" => 3,
            "First five" => 5,
            _ => int.MaxValue,
        };

        var shown = rows.Take(limit).ToList();

        var lines = shown
            .Select(row => string.Join(" ", options.Columns.Select(column => column switch
            {
                "Tag" => row.Tag,
                "Length" => row.Text.Length.ToString(),
                _ => row.Text,
            })))
            .ToList();

        return new FilterResult(lines, total, shown.Count);
    }

It does five things in order: split lines, filter by tag, dedupe, sort, limit, and finally join text by the selected columns. Each step looks at only one field of options. Whatever the UI sends, this does; it doesn’t know whether those values were picked in a dropdown or checked in a checkbox group.

The two switch expressions on Sort and Count dispatch on plain strings. This means adding one sort order means changing two places: the choices in the UI and the case here. That is this sample’s trade-off. With only three options, hard-coding is shorter than defining an enum; when options grow, or when they have to line up with an external interface, you should replace them with constants or an enum rather than let business code depend on UI wording.

7.2 Custom Values and Filtering

Two switches, both affecting only “how convenient picking is”, not the type passed back.

With allowCustomValue on, the user can type a new value straight into the box and press Enter to accept it. The sample’s tag dropdown has it on, because a tag that isn’t in the list may turn up in the task list. For example, “Temporary”. Once typed, what gets submitted is "Temporary", no different from picking it from the list.

It does no validation at all. A typo is a value; a string of spaces is a value (unless you filter it yourself). So this switch suits cases where “the list isn’t complete and users may add to it”; if the list is closed, leave it off. Turning it on gives up the guarantee of “only these options”.

filterable defaults to true, meaning as soon as you type in the box, the list below filters by what you typed. With many options this is essential. Thirty tags with no filtering means making people hunt with their eyes. Set it to false and typing won’t filter; the list stays as it is.

The difference between the two is worth stating clearly. filterable only narrows the list; what you select is still an item from the list. allowCustomValue treats the input itself as a value. The first helps you find things faster; the second lets you pick something outside the list. Turn both on and you get “filter by the input first, and if nothing matches, use the input directly”.

The path for a custom value is: open the dropdown, delete what’s already in the box, type the new value, press Enter. If the box already has a value, typing appends to it. To enter a custom value you have to clear it first, or you end up with a strange string made of “old value + new value” joined together. This is the step most likely to go wrong, and the price of doing no validation.

Once the custom value is in, it becomes the component’s current value, on equal footing with the other options. It shows as a small chip, you can click × to remove it, and it won’t appear in the list when you pick again. It isn’t in choices; it is only this one value. To have it there next time too, you have to add it to choices yourself (that takes state, Chapter 14).

Because this value isn’t constrained by the list, the handler function should tidy it up: trim leading and trailing whitespace, limit the length, block obviously invalid characters. The sample does only the lightest step: Where(tag => tag.Length > 0) drops empty strings. Stricter validation (for example, “a tag may be at most four characters”) belongs in the business library alongside the other rules.

When should you turn filterable off? When there are very few options (say three) and the user can take them all in at a glance. Leaving it on isn’t wrong, but one more box you can type in is one more moment of “should I type?”. With three options, opening the dropdown and clicking directly is faster than typing.

filterable is on by default, and you can see it directly in the sample. There are eight tags; only six show when you open it (numChoicesShown: 6). Type a “To” in the box and the list immediately narrows to “To-do” and “To Confirm”. With dozens or hundreds of options, this switch decides whether the user “finds by typing” or “scans with their eyes”.

7.3 Selection Limit and Number of Choices Shown

Two numeric parameters, governing “how many you can pick” and “how many you see at once”.

maxChoices limits how many items you can pick at most. The sample sets it to 3.

Figure 7-4 Three already selected; clicking the fourth does nothing

Click all four in turn. The first three go in; on the fourth, the value doesn’t change. It isn’t added, there’s no message, and the list still collapses. That feedback is weak, and the user may think they misclicked. So when you set maxChoices, it’s best to write a line like “Select at most three” in info so people know in advance.

info is the small line under a component, label the large text above it. In use, label says “what this is” and info says “what limits or caveats there are”. Several components in this chapter deserve an info: the limit from maxChoices, “there’s more” from numChoicesShown, “you can also type your own” from allowCustomValue. It works without one, but writing one removes half the confusion.

numChoicesShown is how many options the dropdown shows at once; the default is 100. The sample has eight tags and sets it to 6, so you see only six when you open it and have to scroll for the other two. The parameter earns its keep with a hundred options or more. Rendering several hundred rows at once makes the dropdown lag; set it to 10 or 20 and let search and scrolling handle the rest.

It doesn’t affect “how many you can pick”, only “how many you see at once”. One parameter governs selection, the other display; don’t mix them up.

maxChoices and allowCustomValue can be used together. When they are, a value typed in counts as an item too. With a limit of three and three already selected, one more custom value won’t go in either. That’s easy to forget. The limit counts “the number of current values”, no matter whether they were picked from the list or typed by hand.

maxChoices belongs only to Dropdown. CheckboxGroup has no such parameter; you can check as many as you like. To limit the count on a checkbox group, you have to handle it yourself: count them in its Change event and, if over the limit, return an Update that removes the item just added. There’s no ready-made parameter for this, and no need to switch components because of it.

numChoicesShown and filterable are a pair. With many options you adjust both. numChoicesShown makes the dropdown shorter, filterable lets people type to find things. Shorten without filtering and the user has to scroll a long list; filter without shortening and the dropdown covers half the screen as soon as it opens.

The default of numChoicesShown is 100. That number is the dropdown’s height, expanded to fit 100 rows, and has nothing to do with a cap on how many are shown. Anything beyond 100 options needs scrolling. With a thousand options, that expanded height covers half the screen, so either turn it down or group the options (Choice itself doesn’t support grouping; you do it by a naming convention, for example “To-do / Today”).

7.4 How Radio and Checkbox Differ in Their Values

Both components look like something you “check”, but one picks one out of a group and the other is a single toggle.

Radio and single-select Dropdown are the same thing: a group of mutually exclusive options of which there can be only one. The only difference is how they look. Dropdown collapses into a box and shows its options only when opened; Radio spreads all the options on the page so you can see them at a glance. With fewer than five options, when you want the user to see them all at once, Radio is the better fit.

        var count = gr.Radio(label: "Count", choices: new[] { new Choice("All"), new Choice("First three"), new Choice("First five") }, value: "All", interactive: true);

It passes a string to the handler function, the same as a single-select dropdown.

Checkbox has no choices; it is simply a toggle.

        var dedupe = gr.Checkbox(label: "Dedupe by content", value: false);

It passes a bool to the handler function. Its value is a Boolean, not a string, which sets it apart from the ones before. The label says “what happens when you check it”, not “what this toggle is called”. “Dedupe by content” is clearer than “Dedupe”, because checking it really does dedupe by content.

What the two share is “neither needs the user to type”; the difference is semantics. Radio is “pick one of these”, Checkbox is “do this one thing or not”. In the sample, “Count” is three mutually exclusive options, so Radio; “Dedupe” is do-or-don’t, so Checkbox. You can force a toggle into a two-option Radio (“Dedupe” / “Don’t dedupe”) and it works, but one extra option is one extra click.

Radio or Single-Select Dropdown

Both components pass a string to the handler function and are identical in capability; which one you pick depends only on how many options there are and whether you want them all visible at a glance.

SituationUseReason
Two to four optionsRadioAll spread on the page; you know what’s there without opening anything
Five or more optionsSingle-select DropdownSpread out, they’d take up half the screen
Options change with another choiceDropdownCollapsed takes less space and won’t jump when options change
Want to see the current choice without openingRadioThe selected dot is filled, the others are hollow

The sample’s “Count” has only three options, so Radio; if one day you add “First ten”, “First twenty”, “All”, “Keep empty lines only”… once options multiply, switch to a dropdown.

How to Arrange a Group of Toggles

The sample’s filter has five controls, two of which are a do-or-don’t toggle (dedupe) and a pick-one single-select (count). When you place them together, the order is worth a thought. Put “pick which” first, then “do or don’t”. The first decides the scope of the result, the second is processing applied to that result; fixing the scope before the processing reads more naturally.

When several Checkboxes sit side by side, write the label like “do this thing”, not as a noun like “Dedupe”. A noun makes people think it’s another option group; only a verb phrase reads as “checking means doing”. The sample writes “Dedupe by content”, and checking it does dedupe by content, with no ambiguity.

Radio’s options are laid out horizontally by default and wrap when they don’t fit on one line. With many options and long names, a horizontal row squeezes into two or three lines and looks worse than a vertical layout. Switching to Dropdown takes less space here. It also has an rtl parameter for right-to-left languages, which left-to-right text like this does not need.

Checkbox differs from the others in one more place: its value is a bool, not a string. So value: false is right and value: "false" won’t compile. This one saves a bit of confusion when reading someone else’s code.

7.5 CheckboxGroup and Select All

CheckboxGroup is “a group of checkboxes you can multi-select”. It looks like Radio (options spread on the page) but lets you pick several.

        var columns = gr.CheckboxGroup(label: "Which columns to show", choices: new[] { new Choice("Tag"), new Choice("Content"), new Choice("Length") },
            value: new[] { "Tag", "Content" }, showSelectAll: true, interactive: true);

Checking and the value correspond exactly. Check “Tag” and a "Tag" appears in the list; uncheck it and one disappears. There is no in-between state of “checked but it didn’t take”, and no “in the value but unchecked in the UI” — unless you return an Update from the handler function that changes the value, which is another matter (Chapter 5).

It passes an object[] to the handler function, the same as the multi-select dropdown in 7.1.

  • Dropdown(multiselect: true) → object[]
  • CheckboxGroup → object[]

Both components are called “multi-select” and pass back the same container. In the sample’s Filter, tags and columns are both declared as object[], so you don’t need two signatures when writing the handler function.

showSelectAll adds a “Select all” box. This box has three states: empty when none are selected; checked when all are selected; and half-selected when some are selected (a horizontal bar, called indeterminate). Half-selected is neither “none” nor “all”; it is the browser’s third state for a checkbox, used specifically to express “some”. Click it once and it goes from half-selected to all; click again and nothing is selected.

The select-all box saves clicks. With three options you can’t see the benefit; with a dozen or so, wanting them all means a dozen clicks.

Two Multi-Selects, One Container

Both multi-select components now come from the same sequence. The component first puts the selected values into an object[]; before calling the handler function, the framework reads the parameter types in the signature and puts those values into the matching container according to the declaration. Declare it as object[] and the values pass through unchanged; declare it as List<object> and the framework creates a new List<object> and moves the values over; declare it as a list interface such as IReadOnlyList<object?>, which both containers implement, and no conversion is needed.

ComponentValue the component givesThe handler function can declare it as
Dropdown(multiselect: true)object[]object[], List<object>, a list interface
CheckboxGroupobject[]object[], List<object>, a list interface

The sample uses object[] for both sets of values. Conversion happens only at the container level. The elements are still object; declaring List<string> or string[] won’t make the framework convert them one by one, and the call reports a type mismatch. To get strings, you still call ToString() yourself as in 7.1.

The difference between an array and a List here comes down to syntax. An array has a fixed length and uses Length; a List can grow and shrink and uses Count. Both have indexing, iteration, and Select. Which one you pick depends on how the business side wants to handle the set of values, not on whether you used a dropdown or a checkbox group.

What Select All Actually Does

Clicking the select-all box doesn’t just check three boxes; it writes all three option values into the component’s value at once. So the handler function receives the full three items, not a “Select all” marker. Clearing select-all is the same: the value goes back to an empty array.

In other words, showSelectAll is just one more box in the UI; it doesn’t change what’s passed back. The handler function doesn’t need to know whether the user checked items one by one or pressed select all; the values are identical either way. A UI convenience doesn’t necessarily leave a trace in the data.

There’s a practical benefit to using select all for “Which columns to show” in the sample. “Tag” and “Content” are checked by default; if the user wants to change to “Length” only, they can either press select all and then uncheck two items, or simply click the two off. The select-all box here acts as “one click back to wanting everything”. With columns, users usually want “show all columns” or “show only one column”, with few in-between states.

7.6 The Shape of choices and type

choices is a Choice list, and each Choice has two things: a value and a label.

new Choice("todo", "To-do")     // the value is todo, displayed as "To-do"
new Choice("todo")              // value and label are both todo, displayed as "todo"

The first form keeps the two separate. What the user sees is a readable label, while the program receives a stable code. This is the most common form. What the UI shows to people and the value the program uses should not be the same thing. The second form supplies only a value, which is both what is displayed and what is passed back; it suits cases where “the value itself is meant to be read” (the tags in the sample are like this — the same text is both value and label).

A Choice’s value doesn’t have to be a string. Give it a number.

new Choice(1, "one")

What the handler function receives is a double 1, not an int 1. As with Number, a number is a JSON number in transit and becomes a double-precision float when read into C#. Cast it in the handler function if you want an integer.

type decides whether the handler function receives the “value” or the “index”. The three components with options (dropdown, radio, checkbox group) all have this parameter and it means the same in each. Single-select passes one; multi-select passes a set.

typePassed to the handler functionValue the option above sends out
"value" (default)The option’s value"todo"
"index"The option’s position in the list (starting from 0)0

Use index when “you don’t care what the value is, only which one was picked”. It has a hidden risk: change the order of the options and every index changes. So unless the options are fixed and their order never moves, use value.

The Two Forms in the Sample

The two dropdowns in 7.1 are exactly the two typical cases.

tags gets its options from an array in the business library, TaskFilter.AllTags, converted with Select into Choices. This form suits cases where “the options are a piece of data”. The list is maintained on the business side and the UI merely draws it. Add a new tag and the UI has it automatically, with no change here.

sort’s options are three hard-coded Choices. This form suits cases where “the options are just a few branches in the code”. The sort orders map to the three cases in the switch; adding or removing one means changing code, so writing them right here is clearest.

Both forms supply only one value; the label of Choice("Source text") is also “Source text”. The name of a sort order is itself meant to be read by people, so there’s no need to invent a separate English code. When should you split them? When the value needs to stay stable and the label needs to be localized. For example, use "by-length" as the value and “By length” as the label. A stable value means interfaces and saved files don’t break when the wording changes; a changeable label means switching languages touches only the label.

Splitting them has another benefit: the value can carry information. For example, give tags values like "todo", "doing", "done", and the business side can tell what state it is at a glance; if the values carried the display wording too, the business code would fill up with string constants and changing one word would mean a global search. UI wording changes; the values in code shouldn’t follow it. Split the two and changing the wording touches only the second argument of Choice.

type: "index" is used rarely, but there is one case where it beats value: when the options are “a list that changes” and you care only about “which position”. For things like “which column” or “which character”, the value is itself a position, so the index is the most direct choice.

Think through its cost in advance. Suppose today’s options are “Source text”, “By tag”, “By length”, and a user saved a 2 (By length). Tomorrow you insert “By date” in the middle and 2 now means “By date”. Same value, different meaning. value has no such problem, because it is a string and doesn’t drift with the order. So use value by default and index only when “position is the meaning”.

type affects only what is passed back, not the value you pass in. The value given at construction is always an option’s value, never an index. This is easy to remember backwards: assume that writing index means giving value: 1, and the constructor throws (Value: 1 is not in the list of choices).

7.7 Empty Values When Nothing Is Selected

The four components behave differently for “nothing selected”.

Single-select Dropdown selects the first item automatically. Give it no value and the box already holds the first item’s value when the page opens, which is also what the handler function receives. In other words, a single-select dropdown has no “empty” state; it always has a value.

Radio is null when you give it no value. With nothing clicked, the handler function gets null. To give it a default you must write value explicitly (the sample’s “Count” writes value: "All").

Both multi-selects are empty arrays. They are “empty collections”, not null. So iterating over them in the handler function won’t throw, but a null check won’t save you.

Put these four differences together and writing a handler function calls for a decision. “Nothing selected” has three representations across the four components (a default value, null, an empty collection). To unify them, convert to one form at the entry of the handler function — for example, turn everything into “empty collection means nothing selected” and treat the single-select dropdown’s default as “the user picked the first item” rather than “nothing selected”.

ComponentWith no valueCan it express “nothing selected”?
Single-select DropdownSelects the first item automaticallyNo
Multi-select DropdownEmpty arrayYes
RadionullYes
CheckboxfalseYes (false means unchecked)
CheckboxGroupEmpty arrayYes

Only the single-select dropdown row is “No”. This decides that for any field where “leaving it unselected is fine”, don’t use a single-select dropdown — unless you’re willing to give it an “Unlimited” option and let “Unlimited” take the first slot. The sample’s “Sort” is just such a field. There always has to be a sort order, so selecting the first item automatically is fine.

One more easy mix-up: an empty string is not “nothing selected”. If an option’s value happens to be an empty string (new Choice("")), selecting it gives the handler function "" — a perfectly valid string value. That is a different thing from the null or empty array of “nothing selected”. When deciding “was anything selected”, use null or the collection’s length, not string.IsNullOrEmpty. The latter also counts “the user picked an empty value” as nothing selected.

This kind of empty-value trap came up in Chapter 3 (a text box gives "", a number box gives null); selection components add one more, the collection. The rule for deciding is still the same one. Work out what “empty” means in the business logic first, then decide which check to use.

The sample’s tag filter is handled exactly this way. An empty array means “don’t filter by tag”, so everything is kept; select some tags and only those are kept. Because a single-select dropdown has no empty state, the sample uses multi-select for tags. Had it used single-select, “don’t filter” would have been impossible to express.

Why Single-Select Dropdown Has No Empty State

The reason is straightforward: a single-select dropdown always has to show something in its box. Leave the box empty and users think it didn’t load; show “Please select” and that is also an option, which needs a corresponding value when selected. So its default behavior is “select the first item”, keeping a real value in the box at all times.

Radio is different. Its options are spread out; when none is clicked, the page makes that perfectly clear — not a single dot is filled. It doesn’t need “select the first item” to avoid ambiguity, so it can stay empty.

Knowing this gives you two choices when using it. Either give it an explicit default so that “doing nothing” still maps to a concrete behavior (the sample’s “Sort” is like this — the “Source text” default keeps the result at least in order), or switch to multi-select so “empty” can be expressed (the sample’s “Tag”).

Radio is the opposite: it is empty by default, so wanting a default means writing it explicitly. The sample’s “Count” writes value: "All" because “no limit” is the most common starting point. One component has a value by default and the other doesn’t; the way you write them is exactly reversed.

One Way to Unify Empty Values

    // Illustration: treat empty as select all
    var picked = tags.Length == 0 ? TaskFilter.AllTags : tags;

This is the “empty means all” form. Select no tags and it’s treated as selecting all; one conditional expression is enough for the whole check. The sample doesn’t have this line; it uses another form. The options.Tags.Count > 0 check in the business library has the same effect: with no tag condition, filtering is skipped.

The other way round, “empty means do nothing” is an early return: no tags selected, return an empty result and don’t compute further. Both are reasonable; which one you pick depends on what it means in the business logic. “Filter” is usually the former (not filtering means wanting everything); “bulk delete” is usually the latter (with nothing selected there’s nothing to delete).

The sample’s business library chose the first form; the code looks like this.

        if (options.Tags.Count > 0)
        {
            rows = rows.Where(row => options.Tags.Contains(row.Tag)).ToList();
        }

“If tags are empty, skip this filtering step.” With no tag condition, all rows are kept. This line can be so light because the UI has already unified “empty” into “empty collection”; if the UI passed null, this would have to check for null first and the code would gain a layer.

A third way to handle it is “empty can’t be submitted”: turn off the button’s Interactive, or have the business layer throw “Select at least one tag”. This fits cases where “you must pick one”; blocking it in the UI up front is friendlier than reporting an error afterwards.

7.8 Chapter Summary

Dropdown’s multiselect decides single- or multi-select: single-select passes string, multi-select passes object[]. allowCustomValue makes the input itself a value (no validation); filterable only narrows the list. maxChoices limits how many you can pick (extra clicks do nothing, with no message); numChoicesShown limits how many you see at once.

Radio is the same as a single-select dropdown: it passes string and is null when nothing is selected. Checkbox is a toggle: it passes bool and defaults to false. CheckboxGroup can multi-select: it passes object[], and showSelectAll gives it a select-all box that can be half-selected.

Each item in choices is a Choice: you can give only a value (it is both displayed and passed back), or give the value and label separately (the label is shown to people, the value goes to the program). Numeric options pass a double. type: "index" passes an index, and all of them change as soon as the order does.

“Nothing selected” has three representations across the four components: the single-select dropdown picks the first item automatically, Radio is null, and the two multi-selects are empty arrays. Unify them in the handler function before going any further.

One Table to Decide Which to Use

Put this chapter’s four components together and choosing one takes three steps.

What you want to doUsePasses back
Pick one from a long listSingle-select Dropdownstring
Pick several from a long listDropdown(multiselect: true)object[]
Pick one from three or five, all visible at a glanceRadiostring
Pick several from three or five, all visible at a glanceCheckboxGroupobject[]
One thing, do it or don’tCheckboxbool

“A long list” and “three or five” have no hard rule; it depends on what fits on the page. A Radio with five options takes one line, with ten it takes two, and then a dropdown fits better. The same question works in reverse too. A dropdown with three options takes one more click to see them all, so a spread-out Radio is better.

The sample’s filter module uses only five controls yet puts all four components to work: multi-select dropdown (tags), single-select dropdown (sort), radio buttons (count), checkbox group (columns), toggle (dedupe). What it does is simple (filter once by conditions), but it lays out exactly the differences this chapter is about.

Only one thing is new in this chapter: the container type. The components in the first six chapters all passed single values to the handler function; here two components pass a set of values, both object[]. Declaring List<object> works too — the framework swaps the container to match the declaration before the call; the elements are still object, so you convert them yourself if you want strings. The rest repeats the contract from Chapter 3: parameters line up by position, and a type mismatch is an error.

The next chapter switches to a batch of read-only components. They take no input; they only present the result properly. Tables, charts, chats, images — each has its own way of presenting.