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 9. Dataframe and Table Interaction

The components in the first eight chapters all accept “a single value” — a string, a number, an option, or a time. The component in this chapter accepts “a whole table”.

The workbench happens to have a table. A task table is column-shaped data to begin with: Tag, Content, Character count, Due, Done. Earlier chapters flattened it into a single stretch of text (one “Tag Content” per line); filtering cut that text line by line, and display split that text line by line. Flattening to text has the virtue of being simple — one Textbox holds it all — but the user can’t edit a single cell directly, and can’t see at a glance which columns there are.

This chapter spreads it back out into a table. Once it’s spread back, everything the earlier chapters did is still here. Filtering still filters by tag, display still draws the result in five ways. The only thing that changes is “what the task table looks like”: from a stretch of text into a table you can view, search, and edit.

Figure 9-1 The table area: one editable table, one read-only comparison table, three callback panels

The sample adds a fifth block to the shell. Three buttons on the left, two tables and three panels on the right, three comparison tables at the bottom. The two tables have identical columns, with exactly one difference: the top one can be edited, the bottom one can’t. The three panels are this chapter’s callback bench — they show “change something, and what does the server receive”. The three comparison tables at the bottom are teaching scaffolding; delete the whole block once you’re done, and the workbench itself is unaffected.

This chapter follows “first understand it, then be able to edit it, finally be able to get it”: how rows, columns, and headers line up, how datatype sets column semantics, how interactive toggles editing, how width and wrapping are arranged, how search is used, what each of the three events brings back, and whether empty tables and row/column counts can actually be capped.

9.1 Dataframe Rows, Columns, and Headers

Dataframe’s value is two-dimensional: a list of rows, and each row is itself a list of cells.

            var grid = gr.Dataframe(
                value: TaskTable.Cells(TaskTable.FromLines(SampleTasks.Split('\n'))),
                headers: TaskTable.Headers,
                datatype: new[] { "str", "str", "number", "date", "bool" },
                columnWidths: new object?[] { 80, 240, 70, 220, 90 },
                interactive: true,
                showRowNumbers: true,
                showSearch: "search",
                label: "Editable table");

The first line, the value chain, has three layers. SampleTasks is eight lines of text; FromLines turns it into eight TableRows; Cells then flattens each TableRow into five cells. The flattened type is IReadOnlyList<IReadOnlyList<object?>>. The outer layer is rows, the inner layer is columns. Eight rows, five columns — eight lists of length five.

Why flatten to object?? Because the five cells in a row aren’t the same kind of thing. The tag is a string, the character count an integer, the due date a date, done a Boolean. The contract from Chapter 3 still holds here: a component accepts one value, and that value itself can have any structure. object? is their common parent type; once Dataframe receives it, it interprets the columns one by one according to datatype.

The flattening code is a single line, in core.

    public static IReadOnlyList<IReadOnlyList<object?>> Cells(IEnumerable<TableRow> rows) =>
    [
        .. rows.Select(row => (IReadOnlyList<object?>)
            [row.Tag, row.Text, row.Chars, row.Due, row.Done]),
    ];

It doesn’t reference Gradio.NET and doesn’t know how many parameters the table component has. What the UI layer gets is a pile of object?, no different in kind from the strings the earlier chapters got — it just has one more layer. The boundary between business logic and UI stays where it was: TaskTable owns “which five things a row holds”, and Program.cs owns “how those five things are laid out into cells”.

Where do those five things come from? Still the “Tag Content” text from Chapter 7, one item per line. FromLines cuts each line in two, then fills in the other three columns.

    public static IReadOnlyList<TableRow> FromLines(IEnumerable<string> lines)
    {
        var rows = new List<TableRow>();

        foreach (var line in lines)
        {
            var trimmed = line.Trim();
            if (trimmed.Length == 0)
            {
                continue;
            }

            var space = trimmed.IndexOf(' ');
            var tag = space < 0 ? trimmed : trimmed[..space];
            var text = space < 0 ? "" : trimmed[(space + 1)..].Trim();

            rows.Add(new TableRow(
                tag,
                text,
                text.Length,
                FirstDue.AddDays(rows.Count * 2),
                tag is "Completed" or "Archived"));
        }

        return rows;
    }

The first two columns are cut out. Before the first space is the tag, after it the content. The last three columns are computed: the character count is the length of the content, the due date moves two days later per row in row order, and done depends on the tag. “Completed” and “Archived” count as done; everything else counts as not done.

Not one line of this code has anything to do with tables. It does the same thing as in Chapter 3: compute everything the UI is going to show first, and let the UI layer only lay it out. Switching to a table changes none of that division of labor — only that what gets “laid out” is five columns instead of one stretch of text.

headers is the column names, one per column. The sample’s five columns, in order, are Tag, Content, Character count, Due, Done, matching the five fields of TableRow one to one. That correspondence is hand-written; the compiler doesn’t check it. One headers short and the last column has no name; one too many and the extra header has no data under it. Get both wrong and the UI reports no error — it just “looks a bit off”. Misaligned headers and data are the hardest kind of problem to track down, because they look like the content is wrong.

One shortcut is to put the column names in a constant on the business side and have the UI reference that constant only.

    public static readonly string[] Headers = ["Tag", "Content", "Character count", "Due", "Done"];

Headers is defined once in TaskTable, referenced twice in BuildTableView (once for the editable table, once for the read-only one), and once each in AppendRow and ClearTable. Change a column name in one place and all four tables follow.

label is the component’s name, shown in the top-left corner of the table (the light gray “Editable table” in Figure 9-1). It’s the component’s own label; the headers are the column names given by headers. showLabel: false hides it. Both tables set label, because on the page they look nearly identical and without a label you can’t tell which is which.

9.2 datatype and Column Semantics

datatype is a string array, one entry per column, telling the component “what this column is”.

It governs two things: which editor a cell uses, and what type the server receives.

datatypeThe server receivesOn the UI
"str"stringa cell of text
"number"doublea cell with a number
"date"stringa cell with a date and time
"bool"boola checkbox

The date column comes back as a string. In the sample, that column reaches the server as text like 2026-03-02T00:00:00. To compute a number of days from it you have to call DateTime.Parse yourself; to sort by date you have to convert first, then compare. This is another example of the Chapter 3 rule “the component decides what type it accepts”. It’s called date, yet the server receives a string.

The same date column even displays differently in the two tables. In Figure 9-1 the Due column of the top table reads 2026-03-01T16:00:00.000Z, while the read-only table below reads 2026-03-02T00:00:00. One value, two spellings. The editable table parses the date into an instant and displays it in UTC; the read-only table outputs the server’s string verbatim. The eight-hour difference comes from the time zone.

That difference affects how you read the data on the UI. When you make a judgment like “the due date is March 2”, don’t look at the string on the UI — look at the value the server received. It’s the same day as the DateTime the business side put in.

The date shows in ISO format because the component does no localization. It lays the value out verbatim and doesn’t guess whether you want “March 2, 2026” or “03/02/2026”. To display it in a local format you have to format it into a string yourself — but then that column becomes str, and the checkbox and date-parsing benefits disappear with it. It’s a trade-off: if you want “a date a machine recognizes”, accept ISO; if you want “a date that’s comfortable for a person to read”, treat it as text.

What if you leave datatype out? It’s treated as str. Remove that array from the sample and the Boolean column stops being a checkbox and becomes the two words true and false; the date column stops being parsed and shows the server’s string verbatim. The UI instantly degrades from “a table” into “a pile of words arranged in a grid”.

If the array is shorter than the column count, the remaining columns are treated as str. That rule is lenient — lenient enough to be easy to forget. Write only two datatype entries for five columns and the last three quietly degrade to text, with no error visible on the UI.

A type mismatch doesn’t error either. Write “seven” into a number column and the table accepts it; what the server receives is a string of text, not a number. Write “March 2, 2026” into a date column and it displays verbatim; write 2026/3/4 and it recognizes and parses it into an instant. datatype is a hint, not validation. Real validation has to be written in the handler function yourself.

That “no error” rule has one concrete consequence. The sample’s statistics need to count “how many rows are done” from the table, and the code is written like this.

    public static TableReport Summarize(IEnumerable<IReadOnlyList<object?>> rows)
    {
        var all = rows.ToList();
        var done = all.Count(row => row.Count > 4 && IsTrue(row[4]));
        var latest = all.Count == 0 ? "(empty table)" : Convert.ToString(all[^1][1]) ?? "";

        return new TableReport(all.Count, all.Count == 0 ? Headers.Length : all[0].Count, done, latest);
    }

IsTrue handles three cases: a genuine bool, the string "true", and anything else, which counts as not done.

    public static bool IsTrue(object? cell) => cell switch
    {
        bool flag => flag,
        string text => bool.TryParse(text, out var parsed) && parsed,
        _ => false,
    };

Why accept string too? Because in a checkbox column the user doesn’t necessarily only click the checkbox. datatype says bool, but the value the server receives isn’t always well-behaved. One extra branch keeps the statistics from crashing on a single unexpected input.

The Boolean column only recognizes true. Write "true" and it counts as checked; write “no” and it counts as unchecked; write anything else and it also counts as unchecked.

There’s one easy misunderstanding with the number column. The “Character count” column is number, but it and the “Content” column are two spellings of the same thing: change one character of content and the character count should change with it. The table won’t link those for you. After you edit the content, the character-count cell still holds the old value. To make it follow, you’d have to recompute it in the change handler function and write it back; the sample doesn’t do that, because rewriting the whole table would wipe out the cell the user is editing. For tables where “one column depends on another”, the usual answer is to make the dependent column read-only, or not store it at all and compute it on the fly.

9.3 interactive and Editing Behavior

interactive decides whether the table can be edited. The sample states it explicitly for both tables: true for the top one, false for the bottom one. It doesn’t rely on the default, because changing this one parameter changes the behavior of the whole table — writing it out is more reliable than remembering the default.

An editable table has two levels of operation.

One click selects. The cell is framed in orange, a triangle appears to the left of the row-number column, and a vertical three-dot menu appears in the cell’s top-right corner.

Figure 9-2 One click selects the cell; on the right, the row, column, and column cell count are recorded

Selecting isn’t just drawing a frame. It also fires a select event, and those three lines in the “Selected” panel on the right are written by the handler function: row 0, column 1, 8 cells in the column, and the cell contains “Add two screenshots”. Where those three numbers come from is covered in 9.6.

A second click enters edit mode. The cell turns into an input box with the cursor inside. Press Enter, press Tab, or click another cell and the change lands.

The two triangles that appear on selection are the entry points for “whole row” and “whole column” — click one to select an entire row or column; the three-dot menu in the cell’s top-right corner is the cell’s menu. The sample uses none of them, and their being there doesn’t affect anything. The table ships with more than the sample uses; you can ignore what you don’t need.

A read-only table has only the first level. Clicking a cell still highlights it and still fires select, but a second click does nothing and no input box appears.

Figure 9-3 The read-only table can be selected too; the highlight and the panels all respond, you just can’t edit

This is easy to get backwards. interactive: false blocks “editing”, not “touching”. If you want to know which row the user clicked, the select event still brings back the row and column; you don’t need editing for that. The sample binds the same handler function to both tables, and the only difference on the panels is “3 cells in the column” versus “8 cells in the column”, because the bottom table has only three rows.

A read-only table is for reading, not editing. Its typical place is a result preview: a computed table sits there that the user can see, select, and copy, but not change. In the sample it’s the “comparison”. Two treatments of the same data — edit the top one and the bottom one stays put.

Figure 9-4 Edit one cell: the Edited panel holds the old value, the Change panel the new one

After the edit, what the server receives is the whole table, not that one cell. In Figure 9-4 both panels talk about “First row content”. The handler function’s parameter is an entire table, and you pull whichever cell you want out of it yourself. That design matches Chapter 3: a component passes its complete value to the handler function, and a table is no exception.

Sending the whole table back with the request has the advantage that the handler function doesn’t need to know which cell the user changed. To recompute statistics, pass the whole table to the business side and recalculate; to validate, scan from the top. The downside is that a large table gets heavy. Twenty rows is fine; two thousand rows sent on every keystroke costs the network and the server both.

The selection level has its uses too. When a user clicks a row you can show that row’s details elsewhere. The whole row is in row_value, so there’s no need to look it up again. The sample only writes the row and column numbers onto a panel; in a real feature that panel usually becomes a detail view, a small card, or a “delete this row” button. The row number the button needs is exactly the one select brings back.

Code can change the table too. The “Append row” button returns a new table with one more row; the UI swaps in the whole new block and the row numbers run from 1 to 9. That’s the same rule as “a return value replaces a component’s content” from Chapter 3 — except here what’s replaced is an entire table.

(object, object) AppendRow(DataframeTable table)
{
    var rows = table.Rows.ToList();
    rows.Add(TaskTable.Cells(new TableRow("To do", $"New item {rows.Count + 1}", 6, TaskTable.FirstDue.AddDays(rows.Count * 2), false)));

    return (new DataframeTable(TaskTable.Headers, rows), gr.Skip());
}

Two outputs, the second one gr.Skip(). This block has two tables, the editable and the read-only, each taking one output slot; “Append row” should change only the editable table and leave the read-only one as it is, so the second slot gets Skip. Chapter 3 covered what Skip is for; this is its most typical use — one event writing several outputs and changing only some of them.

DataframeTable is the table’s value type, with just two members, Headers and Rows. Building a new table means “copy the headers, swap in new rows”. It’s the same type in events: the handler function’s parameter is it, not a two-dimensional array and not JSON.

9.4 Column Width, Wrapping, and Row Numbers

The easiest way for a table to look bad is width.

columnWidths is one pixel width per column. The sample gives five numbers: Tag 80, Content 240, Character count 70, Due 220, Done 90. The widths are there so the “Content” column gets the lion’s share — it holds a whole sentence, while the other columns hold a few characters, a number, a checkmark.

Leave widths out and the component divides them by content itself. With many columns and long content, the result is often not what you want: short columns get stretched wide, long columns squeezed into a strip. Fixed widths at least guarantee it looks the same every time, and let you decide the ratio between “Content” and “Character count”.

The price of fixed widths is “it might not fit on another machine”. Pixels don’t follow the window; make the browser a bit narrower and the last columns get cut. Responsive widths don’t have that problem, but they redistribute when the column count changes, so the same table looks different on two machines. Fixed widths are chosen for a book’s sample because the screenshots need to be stable; for a real application, the choice depends on whether users mostly use it on a large screen or a small one.

Fixed widths bring a new problem: not fitting. Add up the column widths past the container and the right-hand columns get cut, showing only half. A checkbox gets sliced into a strip, a date keeps only its first few characters. The table itself scrolls horizontally — put the mouse over the body and scroll left and right, or move the active cell with the arrow keys, and the cut columns come back into view.

There’s a crude way to judge “will it fit”: add up columnWidths and compare it with the table container’s width. In the sample the five widths add up to 700, and with the forty-odd pixels of the row-number column they just fit inside the container; one more column and you’d be scrolling horizontally.

When it doesn’t fit, there are three ways to handle text that’s too long for a cell.

Truncate. maxChars cuts by character count and adds an ellipsis after the cut. The sample’s comparison table sets it to 12, and the same passage is reduced to “Wrap by chara…”.

Wrap. wrap: true folds long text into several lines; the cell grows taller and not a single character is lost.

Widen. Increase that column’s width so it fits. Column widths are pixels, not percentages, so widening means adding up the total yourself and keeping the table narrower than its container.

Figure 9-5 Three comparison tables: truncate, wrap, not enough headers

The same passage, truncated on the left and wrapped in the middle: you can see the trade-off at a glance. Truncating saves height but hides part of the text; wrapping shows everything but the row heights don’t line up. A table can have both, but within one column it’s best to be consistent — half truncated and half not makes readers think the content lengths differ.

maxChars affects display only, not the stored value. Set it to 12 and the handler function still receives the whole sentence; the only thing cut is the characters on the UI. That’s the exact opposite of a text box’s maxLength: maxLength stops the user typing more, while maxChars stops the user seeing it all. To limit input length you have to check it in the handler function.

showRowNumbers: true adds a row-number column on the far left. Row numbers are signposts for people: “the one in row 5” is easier to say than “the archived one”. They stick with the original table — after search filters, the numbers are still the original ones (you’ll see this in 9.5).

The row-number column counts in neither headers nor columnWidths. Give five columns widths and you get six columns on the UI, the extra one being row numbers. That column takes part in horizontal scrolling too, but it’s the leftmost column, so it doesn’t have far to go.

showRowNumbers is independent of interactive; a read-only table can have row numbers too. The sample’s read-only table leaves it off because three rows are easy enough to count.

Row height follows the content. Eight rows, one line of text each, fits on one screen; switch to wrap: true and long content stretches to two lines, so the same table is suddenly taller. With dozens of rows one screen isn’t enough and the table pushes the page long. The table is the tallest block on this page, so it usually sits lower down rather than at the very top.

9.5 The Search Box and Filtering Rows

showSearch has three settings: "none", "search", "filter". The default is "none", with no box shown to the right of the header.

The other two both put an input box to the right of the header; the difference is the placeholder inside it — Search... for "search", Filter... for "filter". What happens after you type is the same: only matching rows remain and non-matching ones are hidden. You can’t tell the two modes apart on the UI, so which you pick mostly comes down to which placeholder you prefer.

Figure 9-6 Search for “chapter 5”: only one row remains, still with row number 3

Notice the row number in Figure 9-6. The one remaining row still reads 3, not 1. Searching is “hiding the non-matching rows”, not “re-laying-out a new table”. That’s useful when you talk to users: “row 3” always means the same row, searched or not.

Search is a pure UI action that never reaches the server. In Figure 9-6 the three panels don’t move at all, still showing “No cell has been clicked yet”. Typing a search term fires no event; the handler function has no idea anyone is searching. So search can’t replace a query. To really fetch data by a condition, you have to let the handler function take the condition and filter, as in Chapter 7.

That’s also the search box’s boundary: it can only filter “the rows already on the page”. With eight rows in the table, no matter how precise the search, it’s picking from those eight; to search the twentieth row you first have to send twenty rows up.

Search for a word that doesn’t exist and the header stays, the body is empty, and there’s no “no results” message. If you want users to know a search came up empty, you have to arrange that on the page yourself.

A read-only table can search too. The sample’s read-only comparison table leaves search off, but on or off has nothing to do with interactive; the two parameters mind their own business. A read-only table with search on lets the user filter, view, and select — just not edit.

The search box’s position is fixed to the right of the header; it can’t be moved. For a “search somewhere else”, use an ordinary Textbox plus a button and let the handler function filter. That’s the Chapter 7 approach, and it’s a different thing from the search box here.

There’s also a difference in division of labor. The search box filters “this one table that was already sent up”, with the handler function none the wiser; Chapter 7’s filtering has the handler function recompute by condition, and the result can land on any component. The former is fast — no server round trip, one filter per keystroke; the latter can reach “things that aren’t in the table”, like looking up another data set by tag. Small table with the condition being just “do these characters appear in the text” — use the search box; large table, or more than one filter condition — use a handler function.

9.6 Callbacks for Edit, Select, and Change

The three events fire at different times and bring back different values.

Figure 9-7 Select, Edit, Change: when they fire and what they bring back

select fires when you click a cell and brings back “that cell” and its context.

string OnSelect(DataframeTable table, SelectData pick)
{
    var position = pick.Raw is JsonObject payload && payload["index"] is JsonArray pair
        ? pair.Select(node => node?.GetValue<int>() ?? -1).ToArray()
        : [];

    var row = position.Length > 0 ? position[0] : pick.Index ?? -1;
    var column = position.Length > 1 ? position[1] : -1;
    var columnCells = pick.Raw is JsonObject raw && raw["col_value"] is JsonArray cells ? cells.Count : 0;

    return $"""
        **Select** row {row}, column {column} · {columnCells} cells in the column

        Cell: {pick.Value}
        """;
}

SelectData has four members: Value, Index, Selected, Raw. Value is the value in the cell, Index is the row number, and Selected is the selection state for this once (click a cell and it’s true). The row and column numbers aren’t in Index; you get them from Raw. Raw["index"] is a two-element array, the first being the row, the second the column.

That division is easy to mix up. Index is only a row number; to get “which row and which column” you must go through Raw. The sample’s approach is to pull that array out of Raw first and fall back to Index if it’s not there, keeping both paths open.

Raw also holds two ready-made things: row_value is the whole row, col_value the whole column. The sample uses the length of col_value to report “8 cells in the column”. A count is enough to tell the user how many entries the column has; no need to iterate it yourself.

SelectData, like Progress, is injected by type and doesn’t take up a slot in inputs. The binding above lists only one input, [sheet.Grid], yet the handler function has two parameters, the second filled in by the framework by type. The rule at the end of Chapter 5 gets used once more here.

The other two events are covered together.

string OnEdit(DataframeTable table)
{
    var report = TaskTable.Summarize(table.Rows);

    return $"""
        **Edit** before the change: {report.Rows} rows × {report.Columns} columns

        First row content: {Cell(table, 0, 1)}
        """;
}

OnEdit and OnChange look almost identical; the only difference is that one phrase, “before the change” and “after the change”. The two events really do carry different tables.

  • edit brings back the table before the change. The user types “Write the chapter 5 outline” into a cell, and the first row edit receives is still “Write the chapter 4 outline”.
  • change brings back the table after the change. For the same action, the first row change receives is already the new value.

Need the old value to compare, undo, or log an audit — use edit; need to save the new value or recompute statistics — use change. Bind both and you get “what it changed from and to”, with both ends of one edit in hand.

Three details that are easy to trip over.

It fires even when the value doesn’t change. Double-click into a cell, change nothing, press Tab out — both events still fire, and the tables they bring back are identical. So don’t treat “it fired once” as “the user changed something”. Compare the tables before and after, or compare a particular cell’s value.

The order isn’t fixed. For one submit, edit and change are two independent jobs, and which arrives first isn’t guaranteed. In the sample the two panels each write their own, so the order isn’t visible; if both events wrote to the same output, which one ends up displayed would be undefined.

Each fires twice. For one submit, edit fires twice and change fires twice, with identical content. That has nothing to do with whether an output is declared; the front end sends the same submit twice. Handler functions therefore have to be written to run repeatedly. Appending one log line becomes two; applying one deduction deducts twice. The sample’s handler functions only “compute this piece of text”, so running them twice gives the same result and you can’t tell.

Changing the table from code fires only change. Click “Append row”: the table becomes nine rows, the “Change” panel updates, the “Edited” panel doesn’t move. edit only recognizes a cell a human edited.

triggerMode, Then, Success, Failure — all covered in Chapter 5 — work on tables just the same. All three events are ordinary events and their return value is an ordinary Dependency. The sample sets no parameters on them and uses the defaults.

Which of the three events to pick can be worked backwards from “what you want”.

  • Only need to know which cell the user clicked — use select. It’s the lightest: one click fires it, and it doesn’t bring the whole table.
  • Need both ends of “before and after” — bind both. To display “changed from 7 to 9”, that’s the only way to get it.
  • Only need the new value — bind change. Code-driven table changes fire it too, so one path covers both sources.
  • Only need the moment a human edits — bind edit. Code-driven table changes don’t fire it; that’s the one thing that separates it from change.

Of the four, the one most often bound unnecessarily is edit. Its semantics are narrow: it fires only “when the user finishes an edit”, and it fires even if the value didn’t change. Before binding it, ask one question: do you want the old value, or the signal “the user did something”? Use it for the former; for the latter you have to compare yourself.

9.7 Empty Tables and Row/Column Limits

What happens when you clear the table? The header stays, and the body is left with a single dashed-outline row with a “+” in the middle.

Figure 9-8 After clearing: the header is still there, the body is a single “+” row

object ClearTable(DataframeTable table)
    => new DataframeTable(TaskTable.Headers, []);

Clearing means replacing Rows with an empty array and carrying the headers back unchanged. An empty table and “no table at all” are two different things. With the header still there, the user knows what belongs here; if the whole block vanished, the user would only think the feature was gone.

That “+” row is there to be clicked: one click adds an empty row and you fill it in directly. It’s the table’s own built-in entry for creating a row; you don’t have to write a handler function for it. But it isn’t “pure UI” — once a row is added the table’s value has changed, and change fires once (the “Change” panel goes from “after the change: 0 rows” to “after the change: 1 row”). The sample’s other “Append row” button takes a different route: it returns a new table and brings default values along. The two ways of adding a row coexist without conflicting.

After clearing, the “Change” panel reads “after the change: 0 rows”, and Cell can’t get a value, so it shows “(no such cell)”. In the handler function you have to check the row count before reading a cell; you can’t skip that check.

static string Cell(DataframeTable table, int row, int column)
    => table.Rows.Count > row && table.Rows[row].Count > column
        ? Convert.ToString(table.Rows[row][column]) ?? "(empty)"
        : "(no such cell)";

You need both checks: first whether the row exists, then whether that row has the column. After a user clears and then clicks “Append row”, the first row is there — but if some return ever comes back with rows of uneven length, the second check earns its keep.

Can the number of rows and columns be capped? Look at two declarations first.

rowCount and columnCount are each a two-tuple of a count and a mode ("fixed" or "dynamic"). They sound like “this table has exactly this many rows and columns”, but they don’t. What they declare is a starting point, not an upper bound.

  • More data than declared — no truncation. The right-hand comparison table is the proof: headers gives only two columns, the data gives four, all four columns appear on the UI, and the two extra headers are the sequence numbers 3 and 4. Aligning headers with data when you write the code is easier than guessing those numbers afterward.
  • Less data than declared — no empty rows added. Declare 6 rows with 2 rows of data and the UI shows 2 rows; it won’t add four empty ones waiting to be filled.
  • An empty table isn’t padded to the declaration either. Declare 5 rows with a null value and the UI still shows the header plus one “+” row.

So the sample simply leaves these two parameters out; writing them doesn’t affect display, so it might as well not. To really cap things, count in the handler function: when table.Rows.Count exceeds some limit, throw an exception or return a line of notice the user can see. How to write exceptions and notices is covered by Failure in Chapter 5 and by Chapter 17.

That’s another difference between a table and a text box. A text box has maxLength: hit the limit and you can’t type more. A table has no equivalent — row count, column count, and characters per cell (maxChars only governs display, not storage) all have to be blocked yourself.

Extra columns using sequence numbers as headers has another use: debugging. When there’s more data than headers, it’s usually that the column count Cells flattened doesn’t match Headers. A column suddenly appearing that starts with “5” is faster than counting through the code.

An empty table has another use: build a table from scratch for someone to fill in. Give it an empty array and a set of headers, and the page shows the header plus one “+” row; a few clicks and the user has filled out a table. The sample’s “Clear” takes exactly this route — after clearing, the table is still there and the user can keep adding to it. That’s cleaner than “dropping in a few fake rows as placeholders”: fake data gets taken for real, an empty table doesn’t.

The same code used once for “clear” and once for “create” — the only difference is context. A table’s value is, after all, “headers + rows”; rows being empty makes it a new table.

9.8 Chapter Summary

Dataframe holds an entire table in one component. Its value is a two-dimensional structure, rows on the outside and cells on the inside; headers gives one name per column, datatype one type per column, and both arrays must line up with the data’s columns. Put the column names in a constant on the business side and have the UI reference it; change the constant in one place and both sides stay in sync.

datatype decides the editor and the type the server receives: str is a string, number a double, date a string (ISO format, not DateTime), bool a Boolean. Leave it out and columns are treated as str; make the array short and the remaining columns are str too. A type mismatch doesn’t error — datatype is a hint, not validation, so you write the validation yourself.

The same date value displays in UTC in the editable table and verbatim in the read-only one. Judge dates by the value the server receives, not by the UI.

interactive blocks editing, not touching: a read-only table can still be selected and still fires select. An editable table selects on one click and edits on two; press Enter or Tab to land the change, and the server receives the whole table. Code-driven changes use the return value, and when one event writes several outputs but changes only some, write Skip for the rest.

columnWidths sets widths in pixels; when it doesn’t fit, scroll horizontally. For text that’s too long, truncate with maxChars (adding an ellipsis) or wrap with wrap: true — pick one and stay consistent within a column; maxChars affects display only, not the stored value. showRowNumbers adds a row-number column, which counts in neither headers nor columnWidths.

showSearch has three settings. "none" shows no box; "search" and "filter" both “leave only matching rows after you type”, differing only in the placeholder. Search is a pure UI action that fires no event and doesn’t renumber rows; when nothing matches the body is empty but the header stays; it can only filter rows already on the page.

The three events each cover one part: select brings back the cell’s value, the row number, the whole row, and the whole column; edit brings back the whole table before the change; change gives the whole table after it. Bind both and you have “what changed from and to”. They fire even when the value doesn’t change, the order isn’t fixed, and each fires twice. Handler functions must be safe to run repeatedly — don’t treat “it fired once” as “the user changed something”. Code-driven table changes fire only change.

An empty table is a header plus one “+” row, not a blank space. rowCount and columnCount declare a starting point, not an upper bound: more data isn’t truncated, less data adds no empty rows, and an empty table isn’t padded. To cap it, count in the handler function yourself, and check the row first, then the column.

The data in the table still can’t be saved. Refresh and the eight rows go back to their initial values; edits live only on the page. Saving has to wait for state in Chapter 14.

The next chapter switches to a different kind of content: one chart drawn out, a pile of images arranged into a wall.