Programmatically check/uncheck checkbox in a TreeGrid

Dear Support,

How can I programmatically setting (check/uncheck) checkboxes in the TreeGrid?
First column: ShowCheckBox = true
Sample project: in attachment


Thanks,
Kind Regards, László


Attachment: SyncfusionMvcApplication1_e8914a25.zip

21 Replies 1 reply marked as answer

GL Gowri Loganathan Syncfusion Team August 11, 2020 10:57 AM UTC

Hi Osvald, 
 
Thanks for contacting Syncfusion Forum. 
 
Query: How to progarmatically select/unselect the checkbox in treegrid 
 
We have achieved your requirement using QueryCellInfo event of Tree Grid by adding the e-check class to the specific checkbox satisfying the condition applied. 
 
Code 
@(Html.EJS().TreeGrid("TreeGrid") 
…………………. . . 
            .QueryCellInfo("onquerycellInfo") 
            .Render()) 
………………. .. . 
 
<script> 
    function onquerycellInfo(args) { 
        if (args.data['check'] == 1 && args.column.field == "orderName") { 
            var checkstate = args.cell.querySelectorAll(".e-hierarchycheckbox")[0].children[1] // get the checkbox class here 
            checkstate.classList.add("e-check") // add the e-check class to the specific cell satisfying the condition 
        } 
    } 
</script> 
 
 
 
Output 
 
 
Please refer the below modified sample link, 
 
If you want to program the selection of checkbox externally you can use the method selectCheckBoxes(). 
 
kindly refer the below code to select the checkbox through button click, 
 
Code 
         
   <button onclick="selectcheckbox()">selectcheckbox</button> 
………………… . . 
  function selectcheckbox() { 
                var treegridinstance = document.getElementsByClassName("e-treegrid")[0].ej2_instances[0]   //take treegrid instance here 
        treegridinstance.selectCheckboxes([2,3,6]) //call method here 
    } 
 
 
 
Output 
 
 
 
Kindly get back to us if you need more assistance. 
 
Regards, 
Gowri V L 
 



OL Osvald László replied to Gowri Loganathan August 11, 2020 02:05 PM UTC


Hi Gowri,

Thank You very much. Unfortunately I would not have found a solution 😊

However, I noticed that the group icon does not change (on attached image: 1.)
Another problem is that I have to double-click the checkbox to clear it. (on attached image: 2., with onquerycellinfo).

Thanks!

Regards, László

(Sorry for my bad English)




GL Gowri Loganathan Syncfusion Team August 12, 2020 02:30 PM UTC

Hi Osvald, 

Sorry for the inconvenience caused. 

Query: check/uncheck programmatically 
 
We are able to reproduce the reported issue at our end. To avoid the issue we suggest you to use selectCheckboxes method instead of adding class. In the below sample we have taken rowIndex using the RowDataBound event when the condition satisfied and stored it in a global variable and then pass the index variable to the selectCheckboxes method inside the DataBound event as shown below. 

 
@(Html.EJS().TreeGrid("TreeGrid") 
                    …………………………. 
                    .RowDataBound("onrowDataBound") 
                    .DataBound("databound") 
                    .Render()) 
……………………….. 
<script> 
var index = []; 
    var parentID; 
function onrowDataBound(args) { 
               if (args.data['check'] == 1 ) { 
            if (args.data.hasChildRecords) {  //check whether the parent record has a value check == 1 
                parentID = args.data.ID; 
                index.push(parseInt(args.row.getAttribute("aria-rowindex"))); 
            } else if (args.data.parentItem && parentID !== args.data.parentItem.ID) { 
                index.push(parseInt(args.row.getAttribute("aria-rowindex"))); 
            }                                
        } 
           } 
    function databound(args) {            
        var treegridinstance = document.getElementsByClassName("e-treegrid")[0].ej2_instances[0]; //take treegrid instance here 
        treegridinstance.selectCheckboxes(index); 
 
    } 
</script> 


Output 
 


Kindly get back to us if you need further assistance. 

Regards, 
Gowri V L 


Marked as answer

OL Osvald László August 12, 2020 03:58 PM UTC

Hi Gowri,

Thank you, your solution is perfect!

Regards, László


OL Osvald László August 12, 2020 06:07 PM UTC

Hi Gowri,

Something else came to mind. :)
Based on the image below, how do I make country names appear in MultiSelect instead of ID's?

My example project is in the attachment.

Thank You for Your help!

Regards, Laszlo



Attachment: SyncfusionMvcApplication1Phase2_7c73f0d4.zip


GL Gowri Loganathan Syncfusion Team August 13, 2020 01:54 PM UTC

Hi Osvald, 
 
Thanks for contacting Syncfusion Forum. 
 
Query: How do I make country names appear in MultiSelect instead of ID's? 
 
We have achieved your requirement by returning the text of the multiselect dropdown instead of value. Kindly refer the below code, 
 
@(Html.EJS().TreeGrid("TreeGrid") 
                    ……………………………… . .        
                  .Columns(col => 
                          {                            col.Field("orderName").ShowCheckbox(true).HeaderText("orderName").AllowEditing(false).Width("100").Add(); 
                               col.Field("country").HeaderText("country").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("100").Add(); 
                           }) 
                  .Render()) 
<script> 
……………………. .  
    var multiselect; 
    …………………. . .  
function read() { 
              return multiselect.text;  //return the text to show the countryname  
  } 
    function write(args) { 
            multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: @Html.Raw(Json.Encode(@ViewBag.comboData)), 
            fields: { text: 'text', value: 'value' }, 
            placeholder: "Válasszon országot", 
            value: args.rowData[args.column.field] ? args.rowData[args.column.field].split(',') : null, 
            mode: 'CheckBox' 
        }); 
        multiselect.appendTo(elem); 
    }</script> 
 
Please refer the below screenshots:- 
 
Before update 
 
 
While Update 
 
 
After Update 
 
 
Kindly refer the below API links, 
 
Please get back to us if you need more assistance. 
 
Regards, 
Gowri V L 
 



OL Osvald László August 13, 2020 03:36 PM UTC

Hi Gowri,

Thank You for Your help.
I tried the code, but since I'm now passing an ID's and not a country names, it will also show up in MultiSelect.
Look at the code in the attachment, please (or in the my previous letter: SyncfusionMvcApplication1Phase2_7c73f0d4.zip).

Thank You.

Kind regards, Laszlo

Attachment: SyncfusionMvcApplication1Phase2__Send_641c3784.zip


GL Gowri Loganathan Syncfusion Team August 14, 2020 04:54 PM UTC

  
Hi Osvald, 
  
Thanks for the update. 
  
Query: I'm now passing an ID's and not a country names, it will also show up in MultiSelect. 
  
From the shared query we are able to understand that you want to return the ID instead of Text.  For that you have to use value to return the dropdown data (ID) instead of text. Kindly modify the below highlighted code in your attached sample in last update. 
  
Code, 
@(Html.EJS().TreeGrid("TreeGrid")  
                    ……………………………… . .         
                  .Columns(col =>  
                          { 
………………….. 
                           })  
                  .Render())  
<script>  
……………………. .   
    var multiselect;  
    …………………. . .   
function read() {  
              return multiselect.value;  //return the value to show the ID 
  }  
    function write(args) {  
            multiselect = new ej.dropdowns.MultiSelect({  
            dataSource: @Html.Raw(Json.Encode(@ViewBag.comboData)),  
            fields: { text: 'text', value: 'value' },  
            placeholder: "Válasszon országot",  
            value: args.rowData[args.column.field] ? args.rowData[args.column.field].split(',') : null,  
            mode: 'CheckBox'  
        });  
        multiselect.appendTo(elem);  
    } 
</script>  
  
 
  
Please refer the below screenshots 
  
Before Update 
 
During Update 
  
 
  
Before Update 
 
  
If the above solution doesn’t meet your requirement , kindly get back to us with the below confirmation. 
  1. Whether you want to render the multiselect dropdown with the external dataSource (as like foreign data) in Tree Grid.
  
Regards, 
Gowri V L 
  
  
  
 



OL Osvald László August 15, 2020 01:31 PM UTC

Hi Gowri,

Thank You for Your Help.
I would have one last question.
I converted the project to "datamanager-type", but the data does not appear in the TreeGrid.
I attached the project. Check it out, please.

Thank You so much for Your help so far!

Kind regards, László

Attachment: SyncfusionMvcApplication1Phase2__Send_f28e34df.zip


MP Manivannan Padmanaban Syncfusion Team August 18, 2020 01:56 PM UTC

Hi Osvald, 

Sorry for the delayed response. 

Query: I converted the project to "datamanager-type", but the data does not appear in the TreeGrid. 

We are able to reproduce the reported issue in the shared sample. On further validating, we could see that you have used hierarchy data binding. For remote data we only supported for self-referential data binding. We changed the shared sample for your convenience refer to the link below. 


Regards, 
Manivannan Padmanaban 



OL Osvald László August 19, 2020 11:46 AM UTC

Hi Manivannan,

Thanks. Unfortunately, the childrows don't appear in the example.
What could be the problem? Update: I solved the problem. Missing the .HasChildMapping("isParent") in the grid. :-)
Another problem is that the Update event is not fire in the TreeGridController.

Kind Regards, László




OL Osvald László August 19, 2020 12:40 PM UTC

Hi,

I modified the project (attached) and found that the checkboxes are not selected (in treedata.check = 1).
This worked with the previous solution (August 12, 2020 02:30).
I think there is something wrong with the RowDataBound in the TreeGrid.
Another problem is that he Updata event is not fire in the TreeGridController.
I attached the project. Check it out, please.

Thank You,
Regards, Laszlo

Attachment: SyncfusionMvcApplication1Phase2__Send_80c0aa6b.zip


GL Gowri Loganathan Syncfusion Team August 19, 2020 01:02 PM UTC

Hi Osvald, 
 
Sorry for the inconvenience caused. 
 
Query#1: Child rows not appeared in TreeGrid 
 
In the attached sample the IdMapping is defined wrong which led to the reported issue. So we have modified the IdMapping in the sample and please refer to the below code, 
 
@(Html.EJS().TreeGrid("TreeGrid")                         
DataSource(dataManager => 
{ 
    dataManager 
.Url(@Url.Action("Datasource", "TreeGrid")) 
.UpdateUrl(@Url.Action("Update", "TreeGrid")) 
.Adaptor("UrlAdaptor"); 
 
})                            .Columns(col => 
                            { 
                                ……….. 
                            }) 
                            .IdMapping("TaskId").ParentIdMapping("ParentId") 
                            .AutoCheckHierarchy(true) 
                            .TreeColumnIndex(0) 
                            .Render()) 
 
Query#2: Update event not fired in Tree Grid 
 
We are able to reproduce the reported issue and further analyzing the sample we could see that the model class is not defined properly in serverside update function. To avoid the issue, we suggest you to refer the model class as like below, 
 
 
 
Query#3: I modified the project (attached) and found that the checkboxes are not selected (in treedata.check = 1). 
 
We will validate and provide you the further response by 20th August 2020. 
 
Please get back to us if you need more assistance. We will be happy to assist you. 
 
Regards, 
Gowri V L 
 



GL Gowri Loganathan Syncfusion Team August 19, 2020 01:02 PM UTC

Hi Osvald, 
 
Sorry for the inconvenience caused. 
 
Query#1: Child rows not appeared in TreeGrid 
 
In the attached sample the IdMapping is defined wrong which led to the reported issue. So we have modified the IdMapping in the sample and please refer to the below code, 
 
@(Html.EJS().TreeGrid("TreeGrid")                         
DataSource(dataManager => 
{ 
    dataManager 
.Url(@Url.Action("Datasource", "TreeGrid")) 
.UpdateUrl(@Url.Action("Update", "TreeGrid")) 
.Adaptor("UrlAdaptor"); 
 
})                            .Columns(col => 
                            { 
                                ……….. 
                            }) 
                            .IdMapping("TaskId").ParentIdMapping("ParentId") 
                            .AutoCheckHierarchy(true) 
                            .TreeColumnIndex(0) 
                            .Render()) 
 
Query#2: Update event not fired in Tree Grid 
 
We are able to reproduce the reported issue and further analyzing the sample we could see that the model class is not defined properly in serverside update function. To avoid the issue, we suggest you to refer the model class as like below, 
 
 
 
Query#3: I modified the project (attached) and found that the checkboxes are not selected (in treedata.check = 1). 
 
We will validate and provide you the further response by 20th August 2020. 
 
Please get back to us if you need more assistance. We will be happy to assist you. 
 
Regards, 
Gowri V L 
 



OL Osvald László August 19, 2020 09:27 PM UTC

Hi Gowri! :-)

Thank You very much!
I modified the project (attached) and found that the checkboxes are not selected (in treedata.check = 1).
I tried it anyway, but no good (RowDataBound):



Attachment: SyncfusionMvcApplication1Phase2__Send_b5e688a.zip


GL Gowri Loganathan Syncfusion Team August 20, 2020 01:48 PM UTC

Hi Osvald, 
 
Thanks for contacting Syncfusion Forum. 
 
Query: I modified the project (attached) and found that the checkboxes are not selected (in treedata.check = 1). 
 
When we use remote data in Tree Grid, all the records are rendered in collapsed state and when we expand the parent row, at that time child records are retrieved from the server side which is the default behavior. 
 
 In your case, the parent records have a check value of "0" so that the checked state is not applied for the initial render. Once we have expanded, the child records are bound and based on their check value the state checked is changed. 
 
 If you want to view Tree Grid records in an expanded state on the initial render while using remote data, please get back to us. We are pleased to assist you. 
 
Regards, 
Gowri V L 
 



OL Osvald László August 20, 2020 07:02 PM UTC

Hi Gowri,

I understand and thank You.
It's good if it is closed by default, but it should be self-checked if the child items below it are checked.

In the root(parent) rows how do I set the self-check icon  programmatically, if any of the childrows are checked?
Does not appear when collapsed. The icon only appears when I open the parentrow.

If this is resolved, I will have no more questions.

Self-checked icon: 

Thank You for Your Help!


Regards, László



OL Osvald László August 20, 2020 07:05 PM UTC

Hi,

To my previous letter....

Attachment: SyncfusionMvcApplication1Phase2__Send_4d1ef8e3.zip


GL Gowri Loganathan Syncfusion Team August 25, 2020 06:50 AM UTC

Hi Osvald, 
 
Sorry for the delay in getting back to you. 
 
Query: How to make the parent node self checked in a collapsed state while the child records checked in remote data. 
 
As we said earlier when we use remote data all records are rendered in a collapsed state and when we expand the parent, the child records are fetched from  
the server side. So we recommend that you use the LoadChildOnDemand property to make the parent records in a self-checked state when the child is checked as shown below. 
  
In order to achieve LoadChildOnDemand, we need to collect child records in the server end. If you want to hold the parent records in a collapsed state at the initial rendering, we recommend that you call the collapseAll() method at the dataBound event as shown below. 
 
Code 
@(Html.EJS().TreeGrid("TreeGrid") 
                    ………………. . .  
                    .Columns(col => 
                    { 
                        ……………. . . 
                    }) 
                    .LoadChildOnDemand(true)  //to access child records at initial render 
                    .RowDataBound("onrowDataBound") 
                    .DataBound("databound") 
                    .Render()) 
 
 
function databound(args) { 
        var treegridinstance = document.getElementsByClassName("e-treegrid")[0].ej2_instances[0]; 
       treegridinstance.collapseAll();  //call collapseAll method to collapse parent records at initial render 
    } 
 
Server side code for LoadChildOnDemand 
  public ActionResult UrlDatasource(DataManagerRequest dm) 
        { 
             
            if (dm.Where != null) 
            { 
                DataSource = CollectChildRecords(DataSource, dm); 
            } 
        } 
        public IEnumerable CollectChildRecords(IEnumerable datasource, DataManagerRequest dm) 
        { 
            DataOperations operation = new DataOperations(); 
            IEnumerable DataSource = treeData; // use the total DataSource here 
            string IdMapping = "ID";// define your IdMapping field name here 
            int[] Ids = new int[0]; 
            foreach (var rec in datasource) 
            { 
                int ID = (int)rec.GetType().GetProperty(IdMapping).GetValue(rec); 
                Ids = Ids.Concat(new int[] { ID }).ToArray(); 
            } 
            IEnumerable ChildRecords = null; 
            foreach (int id in Ids) 
            { 
                dm.Where[0].value = id; 
                IEnumerable records = operation.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator); 
                ChildRecords = ChildRecords == null || (ChildRecords.AsQueryable().Count() == 0) ? records : ((IEnumerable<object>)ChildRecords).Concat((IEnumerable<object>)records); 
            } 
            if (ChildRecords != null) 
            { 
                ChildRecords = CollectChildRecords(ChildRecords, dm); 
                if (dm.Sorted != null && dm.Sorted.Count > 0)  
                { 
                    ChildRecords = operation.PerformSorting(ChildRecords, dm.Sorted); 
                } 
                datasource = ((IEnumerable<object>)datasource).Concat((IEnumerable<object>)ChildRecords); 
            } 
            return datasource; 
       } 
 
 
   
Output 
 
 
 
Also please refer to the API links, 
 
Please revert us if you need more assistance. 
 
Regards, 
Gowri V L 
 



OL Osvald László August 25, 2020 03:41 PM UTC

Hi Gowri!

Perfect solution, thank You very much!!

Regards, László


GL Gowri Loganathan Syncfusion Team August 26, 2020 05:42 AM UTC

Hi Osvald, 
 
We are happy to hear that your requirement has been achieved with the given solution. 
 
Kindly get back to us if you need more assistance. 
 
Regards, 
Gowri V L 
 


Loader.
Up arrow icon