# TreeList State

The TreeList lets you read, save, load, and change its state through code. The state includes the TreeList features that are controlled by the user, such as the current sorting, page number, applied grouping, column widths, and many others.

This article describes:

* [The properties of the `TreeListState` object](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#information-in-the-treelist-state).
* [How to set initial TreeList configuration programmatically in `OnStateInit`](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstateinit).
* [How to detect user changes in the TreeList state with `OnStateChanged`](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstatechanged).
* [How to use TreeList methods to get and set the TreeList state](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#methods).
* [Why you may need to override the `Equals` method of the TreeList model class](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#equals-comparison).

## Information in the TreeList State

The TreeList state is a generic [class `TreeListState<TItem>`](https://www.telerik.com/blazor-ui/documentation/api/telerik.blazor.components.treeliststate-1). The type depends on the type of the TreeList model. The `TreeListState<TItem>` object exposes the following properties:

<style>
    .article table {
        table-layout: auto;
        word-break: normal;
    }
</style>

| Property            | Type                               | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ColumnStates`      | `ICollection<TreeListColumnState>` | Information about each [column's reorder index, width, visibility, locked state, `Id` parameter value and `Field`](https://www.telerik.com/blazor-ui/documentation/components/treelist/columns/bound). The column order in the collection matches the column order in the TreeList declaration. On the other hand, the `Index` property matches the current column's position in the UI. **`Id` and `Field` are always `null` after deserialization, because these properties have no public setters.** |
| `EditField`         | `string`                           | The currently edited data item property in [`Incell` edit mode](https://www.telerik.com/blazor-ui/documentation/components/treelist/editing/incell).                                                                                                                                                                                                                                                                                                                                                    |
| `EditItem`          | `TItem`\*                          | The currently edited data item in [any edit mode](https://www.telerik.com/blazor-ui/documentation/components/treelist/editing/overview).                                                                                                                                                                                                                                                                                                                                                                |
| `ExpandedItems`     | `ICollection<TItem>`               | The expanded data items.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `FilterDescriptors` | `ICollection<IFilterDescriptor>`   | A collection of [`CompositeFilterDescriptor`](https://www.telerik.com/blazor-ui/documentation/common-features/data-binding/descriptors#filtering), except the ones that relate to the [`TreeListSearchBox`](https://www.telerik.com/blazor-ui/documentation/components/treelist/filter/searchbox).                                                                                                                                                                                                      |
| `InsertedItem`      | `TItem`\*                          | The data item that is being added in `Inline` or `Popup` edit mode. [Not applicable for `Incell` editing](https://www.telerik.com/blazor-ui/documentation/components/treelist/editing/incell#events).                                                                                                                                                                                                                                                                                                   |
| `OriginalEditItem`  | `TItem`\*                          | The original copy of the data item that is currently in edit mode. This `TreeListState` property holds the unmodified data item values.                                                                                                                                                                                                                                                                                                                                                                 |
| `Page`              | `int?`                             | The current [page index](https://www.telerik.com/blazor-ui/documentation/components/treelist/paging). Some user actions reset the page index to 1, such as filtering or changing the page size.                                                                                                                                                                                                                                                                                                         |
| `ParentItem`        | `TItem?`\*                         | The parent item of the current `InsertedItem` in `Inline` or `Popup` edit mode. The value is `null` is the new item is being added at root level.                                                                                                                                                                                                                                                                                                                                                       |
| `SearchFilter`      | `IFilterDescriptor`                | The [`CompositeFilterDescriptor`](https://www.telerik.com/blazor-ui/documentation/common-features/data-binding/descriptors#filtering) that holds the filter descriptors for the [`TreeListSearchBox`](https://www.telerik.com/blazor-ui/documentation/components/treelist/filter/searchbox).                                                                                                                                                                                                            |
| `SelectedItems`     | `ICollection<TItem>`               | The currently [selected data item(s)](https://www.telerik.com/blazor-ui/documentation/components/treelist/selection/overview).                                                                                                                                                                                                                                                                                                                                                                          |
| `Skip`              | `int?`                             | The number of scrolled data items when using [virtual row scrolling](https://www.telerik.com/blazor-ui/documentation/components/treelist/virtual-scrolling). In other words, this is the number of rows above the currently visible ones.                                                                                                                                                                                                                                                               |
| `SortDescriptors`   | `ICollection<SortDescriptor>`      | The currently applied [sorts](https://www.telerik.com/blazor-ui/documentation/components/treelist/sorting).                                                                                                                                                                                                                                                                                                                                                                                             |
| `TableWidth`        | `string`                           | The sum of all visible column widths. The initial value is always `null` regardless of the column configuration. The `TableWidth` value changes during column resizing together with `ColumnStates` and the`OnStateChanged` event does not fire separately for it. When you resize a column programmatically, and all other columns already have widths, you must update the `TableWidth` too, otherwise the other columns will resize unexpectedly.                                                    |

\* `TItem` is the TreeList model type.

## Events

The TreeList features two events, which are related to its state.

* [OnStateInit](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstateinit)
* [OnStateChanged](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstatechanged)

### OnStateInit

The `OnStateInit` event fires when the TreeList is initializing. Use this event to:

* Define initial state, for example default initial sorting;
* Load and apply state that was previously saved in a database or in `localStorage`.

The generic event argument is of type `TreeListStateEventArgs<TItem>` and has a `TreeListState` property. See [Information in the TreeList State](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#information-in-the-treelist-state) for details.

> If you change the column order or number of columns in the TreeList declaration, this can break state restore. In such cases, either ignore the stored column state, or implement custom logic to restore only the columns that still exist in the TreeList.
>
> To set the initial visibility of columns, better use the `Visible` parameter, rather than conditional markup for the whole column. The `Visible` parameter values will be present in the TreeList state and the columns collection count will remain the same. This makes it easier to reconcile changes.

The example below shows how to apply initial sorting, filtering and grouping.

> caption Using TreeList OnStateInit

<demo metaUrl="client/treelist/state/example-1/" height="720"></demo>

### OnStateChanged

`OnStateChanged` fires when the user performs an action that changes the value of a [property in the TreeList state](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#information-in-the-treelist-state). The event argument is of type `TreeListStateEventArgs<TItem>` and exposes these properties:

| Property        | Type                   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PropertyName`  | `string`               | Information about what changed in the TreeList state. The possible values match the [property names of the `TreeListState` object](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#information-in-the-treelist-state). The possible values for the `PropertyName` are `SortDescriptors`, `FilterDescriptors`, `SearchFilter`, `Page`, `Skip`, `ColumnStates`, `ExpandedItems`, `InsertedItem`, `OriginalEditItem`, `EditItem`. |
| `TreeListState` | `TreeListState<TItem>` | The current (up-to-date) TreeList state object.                                                                                                                                                                                                                                                                                                                                                                                                          |

Here is some additional information about certain `PropertyName` values:

* `EditItem` is used when the user starts editing an existing item.
* `InsertedItem` signifies the user adding a new item in inline or popup edit mode. It's [not applicable for `Incell` editing](https://www.telerik.com/blazor-ui/documentation/components/treelist/editing/incell#events).
* `OriginalEditItem` is used when the user exits edit or insert mode via save or cancel.
* `ColumnStates` is used for several column actions such as hiding, showing, locking, reordering and resizing.

> tip Some user actions will trigger two `OnStateChanged` events with a different `PropertyName` each time. These include filtering and searching. For example, filtering resets the current page to 1. First, the event will fire with `PropertyName` equal to `"FilterDescriptors"`, and then `PropertyName` will be `"Page"`. However, the `TreeListState` property of the event argument will provide correct information about the overall TreeList state in both event handler executions.

> We recommend using an `async Task` handler for the `OnStateChanged` event, in order to reduce re-rendering and avoid blocking UI updates if the handler will wait for a service to save the TreeList state somewhere.

To observe the changes in the TreeList state more easily, copy and run the following example in a local app and at full screen.

Find out how to [get the applied filtering and sorting criteria](https://www.telerik.com/blazor-ui/documentation/common-features/data-binding/descriptors).

> caption Using TreeList OnStateChanged

<demo metaUrl="client/treelist/state/example-2/" height="720"></demo>

## Methods

The `GetState` and `SetStateAsync` methods of the [TreeList instance](https://www.telerik.com/blazor-ui/documentation/components/treelist/overview#treelist-reference-and-methods) let you get and set the current TreeList state on demand at any time *after* [`OnStateInit`](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstateinit).

* `GetState` returns the current TreeList state, so you can save it or [retrieve specific information](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#information-in-the-treelist-state). For example, you can [use `GetState` to get the current filters, sorts, and page number](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-get-filtered-data). Or, you can [get the current TreeList column properties like order index, width, and others)](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-column-state).

* `SetStateAsync` receives an instance of a `TreeListState<TItem>` object and applies it to the TreeList. For example, you can have a button that puts the TreeList in a certain configuration programmatically, for example sort or filter the data, enter or exit edit mode, expand or collapse rows, etc.

If you want to make changes to the current TreeList state:

1. First, get the current state with the `GetState` method.
2. Apply the desired modifications to the obtained `TreeListState` object.
3. Set the modified state object via the `SetStateAsync` method.

> Do not use `GetState()` in the [`OnStateInit`](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstateinit) or [`OnStateChanged`](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstatechanged) events. Do not use `SetStateAsync()` in `OnStateInit`. Instead, get or set the `TreeListState` property of the event argument.
>
> Avoid calling `SetStateAsync` in the TreeList [CRUD methods](https://www.telerik.com/blazor-ui/documentation/components/treelist/editing/overview) (such as `OnUpdate`, `OnEdit`, `OnCreate`, `OnCancel`). Doing so may lead to unexpected results because the TreeList has more logic to execute after these events.

> tip To reset the TreeList state to its initial markup configuration, call `SetStateAsync(null)`.
>
> To reset the TreeList state to a completely new configuration, create a `new TreeListState<T>()` and apply the settings there. Then pass the state object to `SetStateAsync()`.

### SetStateAsync Examples

The tabs below show how to set the TreeList state and control filtering, sorting and other TreeList features.

> tip If you want to set an initial state to the TreeList, use a similar snippet, but in the [`OnStateInit event`](https://www.telerik.com/blazor-ui/documentation/components/treelist/state#onstateinit)

```RAZOR.skip-repl Sorting
@* This snippet shows how to set sorting state to the TreeList from your code *@

@using Telerik.DataSource;

<TelerikButton OnClick="@SetTreeListSort">Set sorted state</TelerikButton>

<TelerikTreeList Data="@Data"
                 ItemsField="@(nameof(Employee.DirectReports))"
                 Reorderable="true"
                 Resizable="true"
                 Sortable="true"
                 Pageable="true" 
                 Width="850px" 
                 @ref="TreeListRef">
    <TreeListColumns>
        <TreeListColumn Field="Name" Expandable="true" Width="320px" />
        <TreeListColumn Field="Id" Editable="false" Width="120px" />
        <TreeListColumn Field="EmailAddress" Width="220px" />
        <TreeListColumn Field="HireDate" Width="220px" />
    </TreeListColumns>
</TelerikTreeList>

@code {
    public TelerikTreeList<Employee> TreeListRef { get; set; } = new TelerikTreeList<Employee>();

    async Task SetTreeListSort()
    {
        var sortedState = new TreeListState<Employee>()
        {
            SortDescriptors = new List<SortDescriptor>()
            {
                new SortDescriptor(){ Member = nameof(Employee.Id), SortDirection = ListSortDirection.Descending }
            }
        };

        await TreeListRef.SetStateAsync(sortedState);
    }

    public List<Employee> Data { get; set; }

    // sample model

    public class Employee
    {
        // hierarchical data collections
        public List<Employee> DirectReports { get; set; }

        // data fields for display
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public DateTime HireDate { get; set; }
    }

    // data generation

    // used in this example for data generation and retrieval for CUD operations on the current view-model data
    public int LastId { get; set; } = 1;

    protected override async Task OnInitializedAsync()
    {
        Data = await GetTreeListData();
    }

    async Task<List<Employee>> GetTreeListData()
    {
        List<Employee> data = new List<Employee>();

        for (int i = 1; i < 15; i++)
        {
            Employee root = new Employee
            {
                Id = LastId,
                Name = $"root: {i}",
                EmailAddress = $"{i}@example.com",
                HireDate = DateTime.Now.AddYears(-i),
                DirectReports = new List<Employee>(), // prepare a collection for the child items, will be populated later in the code
            };
            data.Add(root);
            LastId++;

            for (int j = 1; j < 4; j++)
            {
                int currId = LastId;
                Employee firstLevelChild = new Employee
                {
                    Id = currId,
                    Name = $"first level child {j} of {i}",
                    EmailAddress = $"{currId}@example.com",
                    HireDate = DateTime.Now.AddDays(-currId),
                    DirectReports = new List<Employee>(), // collection for child nodes
                };
                root.DirectReports.Add(firstLevelChild); // populate the parent's collection
                LastId++;

                for (int k = 1; k < 3; k++)
                {
                    int nestedId = LastId;
                    // populate the parent's collection
                    firstLevelChild.DirectReports.Add(new Employee
                    {
                        Id = LastId,
                        Name = $"second level child {k} of {j} and {i}",
                        EmailAddress = $"{nestedId}@example.com",
                        HireDate = DateTime.Now.AddMinutes(-nestedId)
                    }); ;
                    LastId++;
                }
            }
        }

        return await Task.FromResult(data);
    }
}
```

```RAZOR FilterRow
@* This snippet shows how to set filtering state to the TreeList from your code
  Applies to the FilterRow mode *@

@using Telerik.DataSource;

<TelerikButton OnClick="@SetTreeListFilter">Filter From Code</TelerikButton>

<TelerikTreeList Data="@TreeListData"
                 ItemsField="@(nameof(Employee.DirectReports))"
                 Reorderable="true"
                 Resizable="true"
                 Sortable="true"
                 FilterMode="@TreeListFilterMode.FilterRow"
                 Pageable="true"
                 Width="850px"
                 @ref="TreeListRef">
    <TreeListColumns>
        <TreeListColumn Field="Name" Expandable="true" Width="320px" />
        <TreeListColumn Field="Id" Editable="false" Width="150px" />
        <TreeListColumn Field="EmailAddress" Width="220px" />
        <TreeListColumn Field="HireDate" Width="220px" />
    </TreeListColumns>
</TelerikTreeList>

@code {
    private TelerikTreeList<Employee> TreeListRef { get; set; } = new TelerikTreeList<Employee>();

    private async Task SetTreeListFilter()
    {
        var filteredState = new TreeListState<Employee>()
            {
                FilterDescriptors = new List<IFilterDescriptor>()
            {
                new CompositeFilterDescriptor(){
                    FilterDescriptors = new FilterDescriptorCollection()
                    {
                        new FilterDescriptor()
                        {
                            Member = nameof(Employee.Id),
                            MemberType = typeof(int),
                            Operator = FilterOperator.IsGreaterThan,
                            Value = 5
                        }
                    }
                },
                new CompositeFilterDescriptor(){
                    FilterDescriptors = new FilterDescriptorCollection()
                    {
                        new FilterDescriptor()
                        {
                            Member = nameof(Employee.Name),
                            MemberType = typeof(string),
                            Operator = FilterOperator.Contains,
                            Value = "second level"
                        }
                    }
                }
            }
            };

        await TreeListRef.SetStateAsync(filteredState);
    }

    private List<Employee> TreeListData { get; set; }

    // sample model

    public class Employee
    {
        // hierarchical data collections
        public List<Employee> DirectReports { get; set; }

        // data fields for display
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public DateTime HireDate { get; set; }
    }

    // data generation

    // used in this example for data generation and retrieval for CUD operations on the current view-model data
    public int LastId { get; set; } = 1;

    protected override async Task OnInitializedAsync()
    {
        TreeListData = await GetTreeListData();
    }

    async Task<List<Employee>> GetTreeListData()
    {
        List<Employee> data = new List<Employee>();

        for (int i = 1; i < 15; i++)
        {
            Employee root = new Employee
                {
                    Id = LastId,
                    Name = $"root: {i}",
                    EmailAddress = $"{i}@example.com",
                    HireDate = DateTime.Now.AddYears(-i),
                    DirectReports = new List<Employee>(), // prepare a collection for the child items, will be populated later in the code
                };
            data.Add(root);
            LastId++;

            for (int j = 1; j < 4; j++)
            {
                int currId = LastId;
                Employee firstLevelChild = new Employee
                    {
                        Id = currId,
                        Name = $"first level child {j} of {i}",
                        EmailAddress = $"{currId}@example.com",
                        HireDate = DateTime.Now.AddDays(-currId),
                        DirectReports = new List<Employee>(), // collection for child nodes
                    };
                root.DirectReports.Add(firstLevelChild); // populate the parent's collection
                LastId++;

                for (int k = 1; k < 3; k++)
                {
                    int nestedId = LastId;
                    // populate the parent's collection
                    firstLevelChild.DirectReports.Add(new Employee
                        {
                            Id = LastId,
                            Name = $"second level child {k} of {j} and {i}",
                            EmailAddress = $"{nestedId}@example.com",
                            HireDate = DateTime.Now.AddMinutes(-nestedId)
                        }); ;
                    LastId++;
                }
            }
        }

        return await Task.FromResult(data);
    }
}
```

```RAZOR FilterMenu
@* This snippet shows how to set filtering state to the TreeList from your code
  Applies to the FilterMenu mode *@
  
@using Telerik.DataSource;

<TelerikButton OnClick="@SetTreeListFilter">Set filtered state</TelerikButton>

<TelerikTreeList Data="@Data"
                 ItemsField="@(nameof(Employee.DirectReports))"
                 Reorderable="true"
                 Resizable="true"
                 Sortable="true"
                 FilterMode="@TreeListFilterMode.FilterMenu"
                 Pageable="true" 
                 Width="850px" 
                 @ref="TreeListRef">
    <TreeListColumns>
        <TreeListColumn Field="Name" Expandable="true" Width="320px" />
        <TreeListColumn Field="Id" Editable="false" Width="120px" />
        <TreeListColumn Field="EmailAddress" Width="220px" />
        <TreeListColumn Field="HireDate" Width="220px" />
    </TreeListColumns>
</TelerikTreeList>

@code {
    public TelerikTreeList<Employee> TreeListRef { get; set; } = new TelerikTreeList<Employee>();

    async Task SetTreeListFilter()
    {
        var filteredState = new TreeListState<Employee>()
        {
            FilterDescriptors = new List<IFilterDescriptor>()
            {
                new CompositeFilterDescriptor(){
                    FilterDescriptors = new FilterDescriptorCollection()
                    {
                        new FilterDescriptor()
                        {
                            Member = nameof(Employee.Id),
                            MemberType = typeof(int),
                            Operator = FilterOperator.IsGreaterThan,
                            Value = 5
                        }
                    }
                },
                new CompositeFilterDescriptor(){
                    FilterDescriptors = new FilterDescriptorCollection()
                    {
                        new FilterDescriptor()
                        {
                            Member = nameof(Employee.Name),
                            MemberType = typeof(string),
                            Operator = FilterOperator.Contains,
                            Value = "second level"
                        }
                    }
                },

            }
        };

        await TreeListRef.SetStateAsync(filteredState);
    }

    public List<Employee> Data { get; set; }

    // sample model

    public class Employee
    {
        // hierarchical data collections
        public List<Employee> DirectReports { get; set; }

        // data fields for display
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public DateTime HireDate { get; set; }
    }

    // data generation

    // used in this example for data generation and retrieval for CUD operations on the current view-model data
    public int LastId { get; set; } = 1;

    protected override async Task OnInitializedAsync()
    {
        Data = await GetTreeListData();
    }

    async Task<List<Employee>> GetTreeListData()
    {
        List<Employee> data = new List<Employee>();

        for (int i = 1; i < 15; i++)
        {
            Employee root = new Employee
            {
                Id = LastId,
                Name = $"root: {i}",
                EmailAddress = $"{i}@example.com",
                HireDate = DateTime.Now.AddYears(-i),
                DirectReports = new List<Employee>(), // prepare a collection for the child items, will be populated later in the code
            };
            data.Add(root);
            LastId++;

            for (int j = 1; j < 4; j++)
            {
                int currId = LastId;
                Employee firstLevelChild = new Employee
                {
                    Id = currId,
                    Name = $"first level child {j} of {i}",
                    EmailAddress = $"{currId}@example.com",
                    HireDate = DateTime.Now.AddDays(-currId),
                    DirectReports = new List<Employee>(), // collection for child nodes
                };
                root.DirectReports.Add(firstLevelChild); // populate the parent's collection
                LastId++;

                for (int k = 1; k < 3; k++)
                {
                    int nestedId = LastId;
                    // populate the parent's collection
                    firstLevelChild.DirectReports.Add(new Employee
                    {
                        Id = LastId,
                        Name = $"second level child {k} of {j} and {i}",
                        EmailAddress = $"{nestedId}@example.com",
                        HireDate = DateTime.Now.AddMinutes(-nestedId)
                    }); ;
                    LastId++;
                }
            }
        }

        return await Task.FromResult(data);
    }
}
```

```RAZOR Search
@using Telerik.DataSource

<TelerikTreeList @ref="@TreeListRef"
                 Data="@TreeListData"
                 IdField="@nameof(SampleModel.Id)"
                 ParentIdField="@nameof(SampleModel.ParentId)"
                 Pageable="true"
                 Sortable="true">
    <TreeListToolBarTemplate>
        <TreeListSearchBox />
        <TelerikButton Icon="@SvgIcon.Search"
                       ThemeColor="@ThemeConstants.Button.ThemeColor.Primary"
                       OnClick="@OnSearchButtonClick">Search Programmatically</TelerikButton>
        <TelerikButton Icon="@SvgIcon.X"
                       OnClick="@OnClearButtonClick">Clear Search</TelerikButton>
    </TreeListToolBarTemplate>
    <TreeListColumns>
        <TreeListColumn Field="@nameof(SampleModel.Name)" Expandable="true" />
        <TreeListColumn Field="@nameof(SampleModel.Description)" />
    </TreeListColumns>
</TelerikTreeList>

@code {
    private TelerikTreeList<SampleModel>? TreeListRef { get; set; }

    private List<SampleModel> TreeListData { get; set; } = new();

    private async Task OnSearchButtonClick()
    {
        if (TreeListRef != null)
        {
            var treelistState = TreeListRef.GetState();

            var searchString = $"{(char)Random.Shared.Next(97, 123)}{(char)Random.Shared.Next(97, 123)}";

            var cfd = new CompositeFilterDescriptor();

            cfd.LogicalOperator = FilterCompositionLogicalOperator.Or;
            cfd.FilterDescriptors = new FilterDescriptorCollection();

            // Add one FilterDesccriptor for each string column
            cfd.FilterDescriptors.Add(new FilterDescriptor()
            {
                Member = nameof(SampleModel.Name),
                MemberType = typeof(string),
                Operator = FilterOperator.Contains,
                Value = searchString
            });
            cfd.FilterDescriptors.Add(new FilterDescriptor()
            {
                Member = nameof(SampleModel.Description),
                MemberType = typeof(string),
                Operator = FilterOperator.Contains,
                Value = searchString
            });

            treelistState.SearchFilter = cfd;

            await TreeListRef.SetStateAsync(treelistState);
        }
    }

    private async Task OnClearButtonClick()
    {
        if (TreeListRef != null)
        {
            var treelistState = TreeListRef.GetState();

            (treelistState.SearchFilter as CompositeFilterDescriptor)?.FilterDescriptors.Clear();

            await TreeListRef.SetStateAsync(treelistState);
        }
    }

    protected override void OnInitialized()
    {
        for (int i = 1; i <= 500; i++)
        {
            TreeListData.Add(new SampleModel()
            {
                Id = i,
                ParentId = i <= 5 ? null : Random.Shared.Next(1, 6),
                Name = $"{(char)Random.Shared.Next(65, 91)}{(char)Random.Shared.Next(65, 91)} " +
                    $"{(char)Random.Shared.Next(65, 91)}{(char)Random.Shared.Next(65, 91)} {i}",
                Description = $"{(char)Random.Shared.Next(97, 123)}{(char)Random.Shared.Next(97, 123)} " +
                    $"{(char)Random.Shared.Next(97, 123)}{(char)Random.Shared.Next(97, 123)} {i}"
            });
        }
    }

    public class SampleModel
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
    }
}
```

```RAZOR ExpandedItems
@*Expand a root level item on a button click*@

@using Telerik.DataSource;

<div>
    <span>
        <label for="telerikNumerikTextbox">Select the index a root level item</label>
        <TelerikNumericTextBox Min="0" 
                               Max="@Data.Count" 
                               @bind-Value="@ExpandedItemIndex" 
                               Id="telerikNumerikTextbox"/>
    </span>
    <span>
        <TelerikButton OnClick="@SetTreeListExpandedItems">Expand the selected root level item</TelerikButton>
    </span>
</div>

<br />

<TelerikTreeList Data="@Data"
                 ItemsField="@(nameof(Employee.DirectReports))"
                 Reorderable="true"
                 Resizable="true"
                 Sortable="true"
                 FilterMode="@TreeListFilterMode.FilterRow"
                 Pageable="true"
                 Width="850px"
                 OnStateInit="((TreeListStateEventArgs<Employee> args) => OnStateInitHandler(args))"
                 @ref="TreeListRef">
    <TreeListColumns>
        <TreeListColumn Field="Name" Expandable="true" Width="320px" />
        <TreeListColumn Field="Id" Editable="false" Width="120px" />
        <TreeListColumn Field="EmailAddress" Width="220px" />
        <TreeListColumn Field="HireDate" Width="220px" />
    </TreeListColumns>
</TelerikTreeList>

@code {
    public TelerikTreeList<Employee> TreeListRef { get; set; } = new TelerikTreeList<Employee>();
    public int ExpandedItemIndex { get; set; }

    async Task OnStateInitHandler(TreeListStateEventArgs<Employee> args)
    {
        var collapsedItemsState = new TreeListState<Employee>()
        {
            //collapse all items in the TreeList upon initialization of the state
            ExpandedItems = new List<Employee>()
        };

        args.TreeListState = collapsedItemsState;
    }

    async Task SetTreeListExpandedItems()
    {
        var expandedState = new TreeListState<Employee>()
        {
            ExpandedItems = new List<Employee>()
            {
                Data[ExpandedItemIndex]
            }
        };

        await TreeListRef.SetStateAsync(expandedState);
    }

    public List<Employee> Data { get; set; }

    // sample model

    public class Employee
    {
        // hierarchical data collections
        public List<Employee> DirectReports { get; set; }

        // data fields for display
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public DateTime HireDate { get; set; }
    }

    // data generation

    // used in this example for data generation and retrieval for CUD operations on the current view-model data
    public int LastId { get; set; } = 1;

    protected override async Task OnInitializedAsync()
    {
        Data = await GetTreeListData();
    }

    async Task<List<Employee>> GetTreeListData()
    {
        List<Employee> data = new List<Employee>();

        for (int i = 1; i < 15; i++)
        {
            Employee root = new Employee
            {
                Id = LastId,
                Name = $"root: {i}",
                EmailAddress = $"{i}@example.com",
                HireDate = DateTime.Now.AddYears(-i),
                DirectReports = new List<Employee>(), // prepare a collection for the child items, will be populated later in the code
            };
            data.Add(root);
            LastId++;

            for (int j = 1; j < 4; j++)
            {
                int currId = LastId;
                Employee firstLevelChild = new Employee
                {
                    Id = currId,
                    Name = $"first level child {j} of {i}",
                    EmailAddress = $"{currId}@example.com",
                    HireDate = DateTime.Now.AddDays(-currId),
                    DirectReports = new List<Employee>(), // collection for child nodes
                };
                root.DirectReports.Add(firstLevelChild); // populate the parent's collection
                LastId++;

                for (int k = 1; k < 3; k++)
                {
                    int nestedId = LastId;
                    // populate the parent's collection
                    firstLevelChild.DirectReports.Add(new Employee
                    {
                        Id = LastId,
                        Name = $"second level child {k} of {j} and {i}",
                        EmailAddress = $"{nestedId}@example.com",
                        HireDate = DateTime.Now.AddMinutes(-nestedId)
                    }); ;
                    LastId++;
                }
            }
        }

        return await Task.FromResult(data);
    }
}
```

```RAZOR Columns
<TelerikButton OnClick="@ReorderTreeListColumns">Reoder Email and HireDate Columns</TelerikButton>

<TelerikTreeList Data="@Data"
                 ItemsField="@(nameof(Employee.DirectReports))"
                 Reorderable="true"
                 Resizable="true"
                 Sortable="true"
                 Pageable="true"
                 Width="850px"
                 @ref="TreeListRef">
    <TreeListColumns>
        <TreeListColumn Field="Name" Expandable="true" Width="320px" />
        <TreeListColumn Field="Id" Editable="false" Width="120px" />
        <TreeListColumn Field="EmailAddress" Width="220px" />
        <TreeListColumn Field="HireDate" Width="220px" />
    </TreeListColumns>
</TelerikTreeList>

@code {
    public TelerikTreeList<Employee> TreeListRef { get; set; } = new TelerikTreeList<Employee>();

    private async Task ReorderTreeListColumns()
    {
        var treeListState = TreeListRef.GetState();

        var emailColState = treeListState.ColumnStates.ElementAt(2);
        var emailColIndex = emailColState.Index;
        var dateColState = treeListState.ColumnStates.ElementAt(3);
        var dateColIndex = dateColState.Index;

        emailColState.Index = dateColIndex;
        dateColState.Index = emailColIndex;

        await TreeListRef.SetStateAsync(treeListState);
    }

    public List<Employee> Data { get; set; }

    // sample model

    public class Employee
    {
        // hierarchical data collections
        public List<Employee> DirectReports { get; set; }

        // data fields for display
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public DateTime HireDate { get; set; }
    }

    // data generation

    // used in this example for data generation and retrieval for CUD operations on the current view-model data
    public int LastId { get; set; } = 1;

    protected override async Task OnInitializedAsync()
    {
        Data = await GetTreeListData();
    }

    async Task<List<Employee>> GetTreeListData()
    {
        List<Employee> data = new List<Employee>();

        for (int i = 1; i < 15; i++)
        {
            Employee root = new Employee
            {
                Id = LastId,
                Name = $"root: {i}",
                EmailAddress = $"{i}@example.com",
                HireDate = DateTime.Now.AddYears(-i),
                DirectReports = new List<Employee>(), // prepare a collection for the child items, will be populated later in the code
            };
            data.Add(root);
            LastId++;

            for (int j = 1; j < 4; j++)
            {
                int currId = LastId;
                Employee firstLevelChild = new Employee
                {
                    Id = currId,
                    Name = $"first level child {j} of {i}",
                    EmailAddress = $"{currId}@example.com",
                    HireDate = DateTime.Now.AddDays(-currId),
                    DirectReports = new List<Employee>(), // collection for child nodes
                };
                root.DirectReports.Add(firstLevelChild); // populate the parent's collection
                LastId++;

                for (int k = 1; k < 3; k++)
                {
                    int nestedId = LastId;
                    // populate the parent's collection
                    firstLevelChild.DirectReports.Add(new Employee
                    {
                        Id = LastId,
                        Name = $"second level child {k} of {j} and {i}",
                        EmailAddress = $"{nestedId}@example.com",
                        HireDate = DateTime.Now.AddMinutes(-nestedId)
                    }); ;
                    LastId++;
                }
            }
        }

        return await Task.FromResult(data);
    }
}
```

> note If you want to alter the filters for a specific column, do not use more than one `FilterDescriptor` in `FilterRow` mode, and more than two `FilterDescriptors` in `FilterMenu` mode. Otherwise additional descriptors will not show up in the UI. This means that you may need to replace or modify an existing descriptor, rather than add a new one.
>
> Inactive filter descriptors in `FilterMenu` mode are distinguished by their `null` `Value`.

## Equals Comparison

State properties that pertain to data items (for example, edited item or selected items) are typed according to the TreeList model. If you restore such data, make sure to implement appropriate comparison checks - by default the [`.Equals()`](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals) check for a class (object) is a reference check and the reference from the restored state is very unlikely to match the current reference in the TreeList data. Thus, you may want to [override the `.Equals()` method of the TreeList model class](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-save-load-state-localstorage), so that it compares by ID, or otherwise re-populate the models in the state object with the new model references from the TreeList data.

## Examples

You can find multiple examples for using the TreeList state in the following [Knowledge Base articles](https://www.telerik.com/blazor-ui/documentation/knowledge-base):

* [Save and load the TreeList state from `localStorage`](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-save-load-state-localstorage)
* [Save the TreeList state in a WebAssembly app](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-save-state-in-webassembly)
* [Override a user action that changes the TreeList state, for example, sort descending first](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-sort-descending)
* [Initiate programmatic editing or inserting of a TreeList row](https://www.telerik.com/blazor-ui/documentation/knowledge-base/treelist-add-edit-state)
* [Get current TreeList column state (order index, width, and others)](https://www.telerik.com/blazor-ui/documentation/knowledge-base/grid-column-state)

## See Also

* [Live Demo: TreeList State](https://demos.telerik.com/blazor-ui/treelist/persist-state)
* [TreeListState API reference](https://www.telerik.com/blazor-ui/documentation/api/telerik.blazor.components.treeliststate-1)
* [Blazor TreeList](https://www.telerik.com/blazor-ui/documentation/components/treelist/overview)
