Search results

Editing

The TreeGrid component has options to dynamically insert, delete and update records. Editing feature is enabled by using EditSettings property and it requires a primary key column for CRUD operations. To define the primary key, set IsPrimaryKey to true using Column API of that particular column.

razor
edit.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid")
        .Height(270)
        .EditSettings(edit => edit.AllowAdding(true).AllowDeleting(true).AllowEditing(true))
        .DataSource((IEnumerable<object>)ViewBag.datasource)
        .Columns(col =>
        {
            col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(110).TextAlign(TextAlign.Right).Add();
            col.Field("TaskName").HeaderText("Task Name").Width(210).Add();
            col.Field("Priority").HeaderText("Priority").Width(90).Add();
            col.Field("Duration").HeaderText("Duration").TextAlign(TextAlign.Right).Width(110).Add();
        })
        .ChildMapping("Children").TreeColumnIndex(1).Render())
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

You can disable editing for a particular column, by specifying AllowEditing of Column API to false.

Toolbar with edit option

The treegrid toolbar has the built-in items to execute Editing actions. You can define this by using the Toolbar property.

razor
editTools.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid")
        .Height(270)
        .EditSettings(edit => edit.AllowAdding(true).AllowDeleting(true).AllowEditing(true).Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row))
        .DataSource((IEnumerable<object>)ViewBag.datasource)
        .Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })
        .Columns(col =>
        {
            col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(110).TextAlign(TextAlign.Right).Add();
            col.Field("TaskName").HeaderText("Task Name").Width(210).Add();
            col.Field("Priority").HeaderText("Priority").Width(90).Add();
            col.Field("Duration").HeaderText("Duration").TextAlign(TextAlign.Right).Width(110).Add();
        })
        .ChildMapping("Children").TreeColumnIndex(1).Render())
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

Cell edit type and its params

The EditType in Column API is used to customize the edit type of the particular column. You can set the EditType based on data type of the column.

Also, you can customize model of the EditType component through the params inEdit property of Column API.

The following table describes cell edit type component and their corresponding edit params of the column.

Component Example
NumericTextBox params: { decimals: 2, value: 5 }
TextBox -
DropDownList params: { value: ‘Germany’ }
razor
editType.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
         edit.AllowAdding(true);
         edit.AllowDeleting(true);
         edit.AllowEditing(true);
         edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);
       })
       .Load("load")
       .Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(90)
             .ValidationRules(new { required = true, number = true })
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").EditType("stringedit").Width(200)
             .ValidationRules(new { required = true }).Add();
          col.Field("StartDate").HeaderText("Start Date").Width(130)
             .EditType("datetimepickeredit")
             .Edit(new { @params = new { format = "M/d/y hh:mm a" } }).TextAlign(TextAlign.Right).Add();
          col.Field("Approved").HeaderText("Approved").Width(80).EditType("booleanedit")
             .Type("boolean").DisplayAsCheckBox(true)
             .TextAlign(TextAlign.Center).Add();
          col.Field("Progress").HeaderText("Progress").Width(100).EditType("numericedit")
             .Edit(new { @params = new { format = "n" } })
             .TextAlign(TextAlign.Right).Add();
          col.Field("Priority").HeaderText("Priority").Width(100).EditType("dropdownedit").Add();

       }).Height(270).ChildMapping("Children").TreeColumnIndex(1).Render())

<script>
    function load(args) {
        this.columns[2].format = { format: 'M/d/y hh:mm a', type: 'dateTime' };
    }
</script>
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

If edit type is not defined in the column, then it will be considered as the stringedit type (Textbox component).

Cell Edit Template

The cell edit template is used to add a custom component for a particular column by invoking the following functions:

  • create - It is used to create the element at the time of initialization.

  • write - It is used to create the custom component or assign default value at the time of editing.

  • read - It is used to read the value from the component at the time of save.

  • destroy - It is used to destroy the component.

razor
editTemplate.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
      {
          edit.AllowAdding(true);
          edit.AllowDeleting(true);
          edit.AllowEditing(true);
          edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Cell);
      })
       .Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })
       .Columns(col =>
       {
           col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
              .TextAlign(TextAlign.Right).Add();
           col.Field("TaskName").HeaderText("Task Name")
              .Edit(new
              {
                  create = "create",
                  read = "read",
                  write = "write",
                  destroy = "destroy"

              }).Width(230).ValidationRules(new { required = true }).Add();
           col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
              .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
           col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

       }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render())

<script>
    var autoCompleteObj, elem;
    function create(args) {
        elem = document.createElement('input');
        return elem;
    }
    function read(args) {
        return autoCompleteObj.value;
    }
    function destroy(args) {
        return autoCompleteObj.destroy();
    }
    function write(args) {
        var treeGridObj = document.getElementById("TreeGrid").ej2_instances[0];
        autoCompleteObj = new ej.dropdowns.AutoComplete({
            dataSource: treeGridObj.grid.dataSource,
            fields: { value: 'TaskName' },
            value: args.rowData[args.column.field]
        });
        autoCompleteObj.appendTo(elem);

    }
</script>
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

Edit Modes

TreeGrid supports the following types of edit modes, they are:

  • Cell
  • Row
  • Dialog

Cell

In Cell edit mode, when you double click on a cell, it is changed to edit state. You can change the cell value and save to the data source. To enable Cell edit, set the Mode property of EditSettings as Cell.

razor
editCell.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
        edit.AllowAdding(true);
        edit.AllowDeleting(true);
        edit.AllowEditing(true);
        edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Cell);

       })
       .Toolbar(new List<string>() { "Add", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
          col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render())
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Cell edit mode is default mode of editing.

Row

In Row edit mode, when you start editing the currently selected record, the entire row is changed to edit state. You can change the cell values of the row and save edited data to the data source. To enable Row edit, set the Mode property of EditSettings as Row.

razor
editRow.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
        edit.AllowAdding(true);
        edit.AllowDeleting(true);
        edit.AllowEditing(true);
        edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

       })
       .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
           col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render())
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

Dialog

In Dialog edit mode, when you start editing the currently selected row, data will be shown on a dialog. You can change the cell values and save edited data to the data source. To enable Dialog edit, set the Mode property of EditSettings as Dialog.

razor
editDialog.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
        edit.AllowAdding(true);
        edit.AllowDeleting(true);
        edit.AllowEditing(true);
        edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Dialog);

       })
       .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
           col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render())
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

Dialog template

The dialog template editing provides an option to customize the default behavior of dialog editing. Using the dialog template, you can render your own editors by defining the Mode property of EditSettings as Dialog and Template as SCRIPT element ID or HTML string which holds the template.

In some cases, you need to add the new field editors in the dialog which are not present in the column model. In that situation, the dialog template will help you to customize the default edit dialog.

In the following sample, treegrid enabled with dialog template editing.

razor
dialogTemplate.cs
editpartial.cs
editpartialMVC.cs
templateModel.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
        edit.AllowAdding(true);
        edit.AllowDeleting(true);
        edit.AllowEditing(true);
        edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Dialog);
        edit.Template("#dialogtemplate");

       })
       .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
           col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).ActionComplete("actionComplete").Render())

<script>
    function actionComplete(args) {
        if (args.requestType === 'beginEdit' || args.requestType === 'add') {
            var ajax = new ej.base.Ajax({
                url: "/Home/Editpartial", //render the partial view
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ value: args.rowData, isedit: args.requestType === 'beginEdit' })
            });
            ajax.send().then(function (data) {
                $("#dialogTemp").html(data); //Render the edit form with selected record
                args.form.elements.namedItem((args.requestType === 'add' ? 'TaskId' : 'TaskName')).focus();
            }).catch(function (xhr) {
                console.log(xhr);
            });
        }
    }
</script>

<script id="dialogtemplate" type="text/x-template">
    <div id="dialogTemp">
    </div>
</script>
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

public ActionResult Editpartial(TreeData value,bool isedit)
{
    ViewBag.prioritydata = new List<object>() { 
        new { text = "Normal", value= "Normal"},
        new { text = "Critical", value= "Critical"},
        new { text = "Low", value= "Low"},
        new { text = "High", value= "High"},
    };
    return PartialView("editpartial", value);
}
@model TestApplication.Models.TreeData

@*//define the model for store the model values*@

@using Syncfusion.EJ2

<div>
    <div class="form-row">
        <div class="form-group col-md-6">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="TaskId" value=@Model.TaskId.ToString() disabled type='text' name="TaskId" />
                <span class="e-float-line"></span>
                <label asp-for="TaskId" class="e-float-text e-label-top">Task ID</label>
            </div>
        </div>
        <div class="form-group col-md-6">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="TaskName" name="TaskName" value=@Model.TaskName />
                <span class="e-float-line"></span>
                <label asp-for="TaskName" class="e-float-text e-label-top">Task Name</label>
            </div>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-6">
            <ejs-numerictextbox id="Progress" value=@Model.Progress format="C2" placeholder="Progress" floatLabelType="Always"></ejs-numerictextbox>
        </div>
        <div class="form-group col-md-6">
            <ejs-datepicker id="StartDate" value=@Model.StartDate placeholder="Start Date" floatLabelType="Always"></ejs-datepicker>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-12">
            <ejs-checkbox checked="@Model.Approved" label="Approved" id="Approved"></ejs-checkbox>
        </div>
    </div>
</div>

<ejs-scripts></ejs-scripts>
@model MVCApplication.Models.TreeGridData
@*//define the model for store the model values*@

@using Syncfusion.EJ2
@using Syncfusion.EJ2.DropDowns

<div>
    <div class="form-row">
        <div class="form-group col-md-6">
            <div class="e-float-input e-control-wrapper">
                <input value=@Model.TaskId name="TaskId" disabled type='text' />
                <span class="e-float-line"></span>
                <label asp-for="TaskId" class="e-float-text e-label-top">Task ID</label>
            </div>
        </div>
        <div class="form-group col-md-6">
            <div class="e-float-input e-control-wrapper">
                <input name="TaskName" value=@Model.TaskName.ToString() />
                <span class="e-float-line"></span>
                <label asp-for="TaskName" class="e-float-text e-label-top">Task Name</label>
            </div>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-6">
            @Html.EJS().NumericTextBox("Progress").Value(Model.Progress).Format("C2").Placeholder("Progress").Render()
        </div>
        <div class="form-group col-md-6">
            @Html.EJS().DatePicker("StartDate").Value(Model.StartDate).Placeholder("Start Date").Render()
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-12">
            @Html.EJS().CheckBox("Approved").Checked(Model.Approved).Label("Approved").Render()
        </div>
    </div>
</div>

@Html.EJS().ScriptManager()
public class TreeData
    {
        public TreeData() { }

        public int TaskId { get; set; }

        public string TaskName { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        public int Duration { get; set; }

        public int Progress { get; set; }
        public string Priority { get; set; }
        public bool Approved { get; set; }

        public DateTime FilterStartDate { get; set; }
        public DateTime FilterEndDate { get; set; }

        public List<TreeData> Children { get; set; }

        public int? ParentId { get; set; }
    }

The template form editors should have name attribute.

Get value from editor

You can read, format, and update the current editor value in the ActionBegin event at the time of setting requestType to save.

In the following code example, the progress value has been formatted and updated.

    function actionBegin(args) {
        if (args.requestType === 'save') {
            // cast string to integer value.
            args.data['progress'] = parseFloat(args.form.querySelector("#progress").value);
        }
    }

Set focus to editor

By default, the first input element in the dialog will be focused while opening the dialog. If the first input element is in disabled or hidden state, focus the valid input element in the ActionComplete event based on requestType as beginEdit.

    function actionComplete(args) {
        // Set initail Focus
        if (args.requestType === 'beginEdit') {
            (args.form.elements.namedItem('taskName')as HTMLInputElement).focus();
        }
    }

Adding validation rules for custom editors

If you have used additional fields that are not present in the column model, then add the validation rules to the ActionComplete event.

    function actionComplete(args: DialogEditEventArgs) {
        if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
            // Add Validation Rules
            args.form.ej2_instances[0].addRules('progress', {max: 100});
        }
    }

Adding row position

The TreeGrid control provides the support to add the new row in the top, bottom, above selected row, below selected row and child position of tree grid content using NewRowPosition property of EditSettings API. By default, a new row will be added at the top of the treegrid.

The following examples shows how to set new row position as Child in tree grid.

razor
newRow.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
          edit.AllowAdding(true);
          edit.AllowDeleting(true);
          edit.AllowEditing(true);
          edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);
          edit.NewRowPosition(Syncfusion.EJ2.TreeGrid.RowPosition.Child);

       })
      .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
      .Columns(col =>
       {
         col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
            .TextAlign(TextAlign.Right).Add();
         col.Field("TaskName").HeaderText("Task Name").Add();
         col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
            .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
         col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
            .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

       }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render())
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Command column

The command column provides an option to add CRUD action buttons in a column. This can be defined by the Commands property of Column API.

The available built-in command buttons are:

Command Button Actions
Edit Edit the current row.
Delete Delete the current row.
Save Update the edited row.
Cancel Cancel the edited state.
razor
commandcolumn.cs
@using Syncfusion.EJ2.Grids


@{
    List<object> commands = new List<object>();
    commands.Add(new { type = "Edit", buttonOption = new { iconCss = "e-icons e-edit", cssClass = "e-flat" } });
    commands.Add(new { type = "Delete", buttonOption = new { iconCss = "e-icons e-delete", cssClass = "e-flat" } });
    commands.Add(new { type = "Save", buttonOption = new { iconCss = "e-icons e-update", cssClass = "e-flat" } });
    commands.Add(new { type = "Cancel", buttonOption = new { iconCss = "e-icons e-cancel-icon", cssClass = "e-flat" } });
}


@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
       .EditSettings(edit =>
        {
          edit.AllowAdding(true);
          edit.AllowDeleting(true);
          edit.AllowEditing(true);
          edit.ShowDeleteConfirmDialog(true);
          edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

        })
        .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
        .Columns(col =>
         {
           col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
              .TextAlign(TextAlign.Right).Add();
           col.Field("TaskName").HeaderText("Task Name").Add();
           col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
              .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
           col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();
           col.HeaderText("Manage Records").Width("160").Commands(commands).Add();

         }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render()
)
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Custom command

The custom command buttons can be added in a column by using the Commands property of Column API and the action for the custom buttons can be defined in the ButtonOption.Click event.

razor
customcommand.cs
@using Syncfusion.EJ2.Grids


@{
    List<object> commands = new List<object>();
    commands.Add(new { type = "taskstatus", buttonOption = new { content = "Details", cssClass = "e-flat e-details" } }); // custom
}

<script>
    function load() {
        this.columns[4].commands[0].buttonOption.click = function (args) {     //click event for custom command button
            var treegrid = document.getElementById('TreeGrid').ej2_instances[0];  // treegrid instance
            var rowObj = treegrid.grid.getRowObjectFromUID(ej.base.closest(args.target, '.e-row').getAttribute('data-uid'));
            alert(JSON.stringify(rowObj.data));  // display row data
        }
    }
</script>

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
       .EditSettings(edit =>
        {
          edit.AllowAdding(true);
          edit.AllowDeleting(true);
          edit.AllowEditing(true);
          edit.ShowDeleteConfirmDialog(true);
          edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

        })
        .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
        .Columns(col =>
         {
           col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
              .TextAlign(TextAlign.Right).Add();
           col.Field("TaskName").HeaderText("Task Name").Add();
           col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
              .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
           col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
              .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();
           col.HeaderText("Manage Records").Width("160").Commands(commands).Add();

         }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Load("load").Render()
)
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Confirmation messages

Delete confirmation

The delete confirm dialog can be shown when deleting a record by defining the ShowDeleteConfirmDialog as true

razor
deleteConfirm.cs
@using Syncfusion.EJ2.Grids


@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
         edit.AllowAdding(true);
         edit.AllowDeleting(true);
         edit.AllowEditing(true);
         edit.ShowDeleteConfirmDialog(true);
         edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

       })
       .Toolbar(new List<string>() { "Add", "Edit", "Update", "Delete", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
          col.Field("Duration").HeaderText("Duration").Width("110").EditType("numericedit")
             .Edit(new { @params = new { format = "n" } }).TextAlign(TextAlign.Right).Add();

         }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render()
)
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

The ShowDeleteConfirmDialog supports all type of edit modes.

Column validation

Column validation allows you to validate the edited or added row data and it display errors for invalid fields before saving data. TreeGrid uses Form Validator component for column validation. You can set validation rules by defining the ValidationRules in Column API.

razor
validationRule.cs
@using Syncfusion.EJ2.Grids


@{
    var dict = new Dictionary<string, object>();
    dict.Add("number", true);
    dict.Add("min", 0);
}

@(Html.EJS().TreeGrid("CellEditType").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
         edit.AllowAdding(true);
         edit.AllowDeleting(true);
         edit.AllowEditing(true);
         edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

        })
        .Load("onLoad").Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })
        .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(70)
             .ValidationRules(new { required = true, number = true })
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").EditType("stringedit").Width(180)
             .ValidationRules(new { required = true }).Add();
          col.Field("StartDate").HeaderText("Start Date").Width(180)
             .EditType("datetimepickeredit").ValidationRules(new { date = true })
             .TextAlign(TextAlign.Right).Add();
          col.Field("Approved").HeaderText("Approved").DisplayAsCheckBox(true).TextAlign(TextAlign.Center).Type("boolean").EditType("booleanedit").Width(90).Add();
          col.Field("Progress").HeaderText("Progress").Width(100).EditType("numericedit")
             .ValidationRules(dict).Edit(new { @params = new { format = "n" } })
             .TextAlign(TextAlign.Right).Add();
          col.Field("Priority").HeaderText("Priority").EditType("dropdownedit").Width(100)
             .ValidationRules(new { required = true }).Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render()
)

<script>
    function onLoad() {
        var treegridObj = document.getElementById("CellEditType").ej2_instances[0];
        for (i = 0; i < treegridObj.columns.length; i++) {
            if (treegridObj.columns[i].field == "StartDate") {
                treegridObj.columns[i].format = { type: 'dateTime', format: 'M/d/y hh:mm a' };
            }
        }
    }
</script>
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Custom validation

You can define your own custom validation rules for the specific columns by using Form Validator custom rules.

In the below demo, custom validation applied for Priority column.

razor
validationRule.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
         edit.AllowAdding(true);
         edit.AllowDeleting(true);
         edit.AllowEditing(true);
         edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

        })
        .Load("onLoad").Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })
        .Columns(col =>
        {
            col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(70)
               .ValidationRules(new { required = true, number = true })
               .TextAlign(TextAlign.Right).Add();
            col.Field("TaskName").HeaderText("Task Name").EditType("stringedit").Width(180)
               .ValidationRules(new { required = true }).Add();
            col.Field("StartDate").HeaderText("Start Date").Width(180)
               .EditType("datetimepickeredit").ValidationRules(new { date = true })
               .TextAlign(TextAlign.Right).Format("yMd").Add();
            col.Field("Priority").HeaderText("Priority").Width(100)
               .Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render()
)

<script>
    function customFn(args) {
        return args['value'].length >= 4;
    }
    function onLoad() {
        this.columns[3].validationRules = { required: true, minLength: [customFn, 'Need atleast 5 letters'] };
    }
</script>
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Default column values on add new

The treegrid provides an option to set the default value for the columns when adding a new record in it. To set a default value for the particular column by defining the DefaultValue in Column API.

razor
defaultvalue.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
         edit.AllowAdding(true);
         edit.AllowDeleting(true);
         edit.AllowEditing(true);
         edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

       })
       .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).Add();
          col.Field("Priority").HeaderText("Priority").Width("110").DefaultValue("Normal").Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render()
)
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.datasource = tree;
    return View();
}

Disable editing for particular column

You can disable editing for particular columns by using the AllowEditing property of Column API.

In the following demo, editing is disabled for the Start Date column.

razor
disable.cs
@using Syncfusion.EJ2.Grids

@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
      .EditSettings(edit =>
       {
         edit.AllowAdding(true);
         edit.AllowDeleting(true);
         edit.AllowEditing(true);
         edit.Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row);

       })
       .Toolbar(new List<string>() { "Add", "Edit", "Update", "Cancel" })
       .Columns(col =>
        {
          col.Field("TaskId").HeaderText("Task ID").IsPrimaryKey(true).Width(120)
             .TextAlign(TextAlign.Right).Add();
          col.Field("TaskName").HeaderText("Task Name").Add();
          col.Field("StartDate").HeaderText("Start Date").Width(150).Format("yMd")
             .EditType("datepickeredit").TextAlign(TextAlign.Right).AllowEditing(false).Add();
          col.Field("Priority").HeaderText("Priority").Width("110").Add();

        }).Height(400).ChildMapping("Children").TreeColumnIndex(1).Render()
)
public IActionResult Index()
{
    var tree = TreeData.GetDefaultData();
    ViewBag.dataSource = tree;
    return View();
}

Troubleshoot: Editing works only for first row

The Editing functionalities can be performed based upon the primary key value of the selected row. If IsPrimaryKey is not defined in the treegrid, then edit or delete action take places the first row.