We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Data Grid mapping to xaml with List of Dictionaries as the ItemsSource collection

Hi

Could you please tell how to bind sfdatagrid to xaml Xamarin MVVM approach when the item source is a List of dictionaries?

A sample project or example would be really helpful.

Thanks
Harsha Kandalam

17 Replies

HA Harsha August 12, 2016 07:51 AM UTC

Forgot to mention..

how to display items in the grid if the columns aren't known at compile time


DD Dharmendar Dhanasekar Syncfusion Team August 15, 2016 05:21 AM UTC

Hi Harsha,

Thanks for contacting Syncfusion Support.

Regarding “To set a Dictionary as the ItemsSource of the SfDataGrid”, it is not possible as the dictionary provides only two properties Key and Value which will be considered as the MappingName for the SfDataGrid columns. Hence only two columns will be created when a dictionary is set as itemssource to the SfDataGrid. 

With regard to“Displaying items in the grid when we columns arent known at compile time”. Xamarin.Forms do not have a support to Dynamic binding. Hence it is not supported in SfDataGrid. Please refer to the below link for further details.

Bugzilla link: https://bugzilla.xamarin.com/show_bug.cgi?id=37071  

Regards,
Dharmendar
 



BE Beej June 23, 2017 07:12 AM UTC

In case helpful for others searching here... binding to Collection<Dictionary<,>> can be accomplished but doesn't appear to be well documented... this WPF SfDataGrid doc gave clue.

The basic trick is to set the SfDataGrid's column.MappingName = "Fields[FieldName]";

     where Fields is a Dictionary property on your List


I couldn't get List<Dictionary<string, object>> working directly without the wrapper class "hiding" the dictionary from what I think is an SfDataGrid bug. The app crash exception call stack ultimately winds up on an invalid Linq related get_Item() call.


Below is sample working code including "SimpleTable" wrapper for List and Newtonsoft type converter for deserializing Json "table" directly into this datastructure.


FYI, I believe there is also a bug with SfDataGrid column sorting logic when bound to this kind of Dictionary, a non-fatal exception fires. I worked around by implementing grid.SortColumnsChanging.


Sample Deserialize call:

var data = "[{\"Source\":\"Web\",\"Batch Id\":1}, {\"Source\":\"Manual\",\"Batch Id\":2}]";

var table = JsonConvert.DeserializeObject<SimpleTable>(data);


Binding sample with crucial MappingName syntax:


grid.ItemsSource = table;

grid.Columns.Add(new GridTextColumn()

{

  HeaderText = "Source",

  MappingName = "Vals[Source]" // **** HERE'S THE KICKER ****

});


SimpleTable.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Newtonsoft.Json;


namespace DataHelpers

{

  [JsonConverter(typeof(DictRow_DictDeserializer))]

  public class DictRow

  {

    public Dictionary<string, object> Vals { get; set; }

    public DictRow(Dictionary<string, object> dict) { Vals = dict; }

  }


  public class SimpleTable : List<DictRow>

  {

    public SimpleTable(IEnumerable<DictRow> list) : base(list) { }

  }


  public class DictRow_DictDeserializer : JsonConverter

  {

    public override bool CanRead => true;

    public override bool CanWrite => false;

    public override bool CanConvert(Type objectType) => objectType == typeof(Dictionary<string, object>);


    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

    {

      return new DictRow(serializer.Deserialize<Dictionary<string, object>>(reader));

    }


    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

    {

      throw new NotSupportedException();

    }

  }

}  



AN Ashok N Syncfusion Team June 27, 2017 06:31 PM UTC

Hi Beej, 
 
We are preparing the sample for Knowledge Base with sorting using Dictionary and we will update the KB link here, once KB was published in online. We appreciate your patience until then. 
 
Regards, 
Ashok 



KI kishor July 24, 2017 05:20 AM UTC

I am also interested in "sample for Knowledge Base with sorting,grouping,filtering,etc". Please suggest date to get this available,if you can.



SS Suhasini  Suresh Syncfusion Team July 25, 2017 01:44 PM UTC

Hi Beej, 
 
Thanks for your patience. 
 
The Knowledge base for loading dynamic items in datagrid is published with enable Sorting and Grouping. Please find the Knowledge base link for your requirement below: 
 
 
Regards, 
Suhasini 



SS Suhasini  Suresh Syncfusion Team July 25, 2017 01:45 PM UTC

Hi Kishor, 
 
Already we have published Knowledge base for loading dynamic items in datagrid with enable Sorting and Grouping. Please find the Knowledge base link for the same below: 
 
 
In the below sample we have enable the Filtering also using SfDataGrid.View.Filter property to achieve your requirement. 
 
 
Regards, 
Suhasini 



BE Beej July 25, 2017 05:19 PM UTC

Thanks for the sample! The need for GridQueryableCollectionViewWrapper looks to be very enlightening.

FYI for other folks copying this code, the JsonConverter approach in the code I provided looks to save an extra iteration through the rows of Json data vs the PopulateData method in the Syncfusion sample.



AN Ashok N Syncfusion Team July 26, 2017 07:01 PM UTC

Hi Beej, 
 
Thanks for you update. We will check and change the code for avoiding extra iteration if needed, also we will modify the KB sample.   
 
Regards, 
Ashok 



KI kishor July 31, 2017 01:28 PM UTC

Thanks. It work great for filter, group, sort but did not work with following1) All groups are by default expanded. i cannot play with expand and collapse feature?  [work great if we set AllowGroupExpandCollapse = true;]2) How can we apply grouping on multiple columns for example in  GridWithJSONData-2047590529 group on FirstName and then on LastName3) how can i show summary of certain column in Column and Row? 4) Conditional formatting?5) Pull to refresh? [Working great]6) Column Drag, Drop, hide ?7) Exporting?8) Freeze Panes?In short how can we achieve all features on data grid. if it is not possible for all in that case which are those we can implement and how?


AN Ashok N Syncfusion Team August 1, 2017 06:31 PM UTC

Hi Kishor, 
 
We regard to inform you that Xamarin.Forms do not have a support for Dynamic binding, so we can’t able to provide all SfDataGri feature support for dynamic collection. We will provide all support in our SfDataGrid after Xamarin.Forms support the dynamic collection. 
 
Regards, 
Ashok  



BE Beej August 3, 2017 08:14 PM UTC

Kishor, for conditional formatting, did you see the Conditional Styles example?

and otherwise using GridTemplateColumn we can completely customize the content & format of every cell based on our desired logic

do those cover what you're trying to accomplish with regards to conditional formatting or perhaps you could elaborate a little further?

Along these lines, beyond simply implementing OnAutoGeneratingColumn which exposes basic text column styling properties... we've had good success with implementing our own "auto generating columns" functionality which then applies various logic based content and formatting ... as a tip into this approach, we disabled the native autogenerate and trigger our logic via "OnPropertyChanged" looking for PropertyName == "ItemSource"... and then loop over the ((SimpleTable)ItemSource)[0].Vals.Keys to know what columns we wish to add to the SfDataGrid.Columns collection.

i can't offer insight for your other needs regarding grouping and such, as i have not explored that far myself yet.

i encourage you to press on with the support folks on the forum here. i've found that asking different ways and suggesting potential approaches will lead them to disclose further enlightenment about what might indeed work... this thread on how to bind to a list of dictionaries, which started out to the contrary, is a perfect example.

best of luck to you


VP Vimal Prabhu Manohkaran Syncfusion Team August 4, 2017 08:08 PM UTC

Hi Kishor,

As Beej stated, you can achieve your requirement of conditional styling and column template customizations through the links he had directed. However regarding your query please refer the below UG links to achieve your requirements,

1. GroupExpandCollapse : https://help.syncfusion.com/xamarin/sfdatagrid/grouping#expand-groups-while-grouping
2. MultiColumnGrouping : Currently not available in grid. You can expect the feature to be available in any of our upcoming releases post 2017 Vol 3 Main Release
 
3. Summary of columns : https://help.syncfusion.com/xamarin/sfdatagrid/summary
4. Conditional Formatting : As Beej stated, https://help.syncfusion.com/xamarin/sfdatagrid/conditional-styles
5. PullToRefresh : https://help.syncfusion.com/xamarin/sfdatagrid/pull-to-refresh
6. Column DragAndDrop : https://help.syncfusion.com/xamarin/sfdatagrid/columndraganddrop
7. Exporting : https://help.syncfusion.com/xamarin/sfdatagrid/exporting
8. FreezePanes : https://help.syncfusion.com/xamarin/sfdatagrid/freeze-panes

We will also be publishing a sample with all features of datagrid included shortly via a KB document.

Regards,
Vimal Prabhu



KI kishor August 14, 2017 10:08 AM UTC

Thanks...

Please find below my remarks. Only 7 No point is throwing exception, rest we can achieve....

1. GroupExpandCollapse : Done. work great if we set AllowGroupExpandCollapse = true;
2. MultiColumnGrouping : Ok
3. Summary of columns : Done
4. Conditional Formatting : Done
5. PullToRefresh : Done
6. Column DragAndDrop : Done
7. Exporting : throws exception as explain below
8. FreezePanes : Done

But throws exception for Exporting feature. I have use code snapshot to export in excel same as give in
https://help.syncfusion.com/xamarin/sfdatagrid/exporting.but it throws exception as "Unhandled Exception:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: firstRow or lastRow occurred"

Please guide me on this.


VP Vimal Prabhu Manohkaran Syncfusion Team August 15, 2017 12:40 PM UTC

Hi Kishor,

Thanks for the update. We have prepared a sample based on your requirements by loading a List of Dictionaries as ItemsSource for SfDataGrid with exporting to PDF and Excel support provided via button click and we were not able to experience any crash. Please refer the sample from the below link to check and overcome the reported crash.

Sample Link : http://www.syncfusion.com/downloads/support/forum/125388/ze/SfDataGridTest-379781147

Regards,
Vimal Prabhu
 



KI kishor August 16, 2017 07:19 AM UTC

Thanks. Please check attached sample where you will get the mentioned issue. I have crossed check your provided sample this work great but for my sample it crashes.


Attachment: Export_To_Excel_7ab80814.rar


AN Ashok N Syncfusion Team August 22, 2017 10:26 AM UTC

Hi Kishor,  
  
Thanks for your update.  
  
We are able to reproduce the reported issue while exporting our SfDataGrid with TableSummary. Fix for this issue will be available in our 2017 Vol 3 SP1 release. Which will be schedule for rolls out end of August 2017. We appreciate your patience until then.  
  
Regards,  
Ashok  


Loader.
Up arrow icon