How do I call my URL for json in Xamarin.Forms.DataGrid

Fourie Laing 21 Reputation points
2021-03-09T10:42:27.093+00:00

I used this link (https://www.c-sharpcorner.com/article/xamarin-forms-datagrid/) to display items in my data grid and it works perfectly. I now want to use a URL to call my JSON data. My code looks the same as in the tutorial.

I've looked on the Internet but cannot find a solution.

Any help would be appreciated.

Model

    public class MistHeader
    {
        public string Company { get; set; }
        public string PaymentType { get; set; }
        public string RecievedDate { get; set; }
        public string RequestNo { get; set; }
        public string SupplierName { get; set; }
        public string QuoteNo { get; set; }
        public string Total { get; set; }
        public string Justification { get; set; }
        public string OrderNumber { get; set; }
    }

    public class Root
    {
        public List<MistHeader> MistHeader { get; set; }
    }

ViewModel

public class ApprovalPageViewModel : INotifyPropertyChanged
    {
        private bool _isRefreshing;

        public ObservableCollection<MistHeader> MistHeaders { get; set; }

        public bool IsRefreshing
        {
            get
            {
                return _isRefreshing;
            }
            set
            {
                _isRefreshing = value;
                OnPropertyChanged(nameof(IsRefreshing));
            }
        }
        public ICommand RefreshCommand { get; set; }

        public ApprovalPageViewModel()
        {
            MistHeaders = new ObservableCollection<MistHeader>();

            GetData();
            RefreshCommand = new Command(CmdRefresh);
        }

        private async void GetData()
        {
            string requestUrl = URL.MistHeaders;
            using (var client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(requestUrl);
                try
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        string content = await response.Content.ReadAsStringAsync();
                        Root root = JsonConvert.DeserializeObject<Root>(content);
                        List<MistHeader> mistHeaders = root.MistHeader;

                        foreach (var item in mistHeaders)
                        {
                            MistHeaders.Add(item);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("\tERROR {0}", ex.Message);
                }
            }
        }

        private async void CmdRefresh()
        {
            IsRefreshing = true;
            await Task.Delay(3000);
            IsRefreshing = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

I've changed the code to what Leon Lu provided.
But I get "Object reference not set to an instance of an object."

Developer technologies .NET Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-03-09T12:04:18.493+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    I can add the link with the JSON data in if that will help

    Based on your Json data, I add the following class in my project.

       using Newtonsoft.Json;  
       using System;  
       using System.Collections.Generic;  
       using System.Text;  
         
       namespace XFDataGrid.Models  
       {  
         
           public class Table  
           {  
               public string Company { get; set; }  
               public string PaymentType { get; set; }  
               public DateTime RecievedDate { get; set; }  
         
               [JsonProperty("RequestNo.")]  
               public string RequestNo { get; set; }  
               public string SupplierName { get; set; }  
         
               [JsonProperty("QuoteNo.")]  
               public string QuoteNo { get; set; }  
               public double Total { get; set; }  
               public string Justification { get; set; }  
               public int OrderNumber { get; set; }  
           }  
         
           public class Root  
           {  
               public List<Table> Table { get; set; }  
           }  
         
         
       }  
    

    Please add Newtonsoft.Json and System.Net.Http to you all of project.

    75796-image.png

    Then open MainPageViewModel.cs., I add GetData method to Deserialize your json data.

       // 16:48  
       using Newtonsoft.Json;  
       using System;  
       using System.Collections.Generic;  
       using System.Collections.ObjectModel;  
       using System.ComponentModel;  
       using System.Net.Http;  
       using System.Threading.Tasks;  
       using System.Windows.Input;  
       using Xamarin.Forms;  
       using XFDataGrid.Models;  
       using XFDataGrid.Utils;  
         
       namespace XFDataGrid.ViewModels  
       {  
           public class MainPageViewModel : INotifyPropertyChanged  
           {  
               private bool _isRefreshing;  
         
               public ObservableCollection<Table> Professionals { get; set; }  
         
         
               public bool IsRefreshing  
               {  
                   get  
                   {  
                       return _isRefreshing;  
                   }  
                   set  
                   {  
                       _isRefreshing = value;  
                       OnPropertyChanged(nameof(IsRefreshing));  
                   }  
               }  
         
               public ICommand RefreshCommand { get; set; }  
               
                 
               public MainPageViewModel()  
               {  
         
                   Professionals = new ObservableCollection<Table>();  
         
                   GetData();  
                   RefreshCommand = new Command(CmdRefresh);  
         
                  
               }  
         
               private async void GetData()  
               {  
                    
         
                   string requestUrl = "https://mist.zp.co.za:6502/MIST.svc/head/M@H$@203@R";  
                   using (var client = new HttpClient())  
                   {  
                       HttpResponseMessage response = await client.GetAsync(requestUrl);  
                       if (response.StatusCode == System.Net.HttpStatusCode.OK)  
                       {  
                           string content = await response.Content.ReadAsStringAsync();  
                           Root root = JsonConvert.DeserializeObject<Root>(content);  
                           List<Table> dates = root.Table;  
         
                          
                           foreach (var item in dates)  
                           {  
                                 
                               Professionals.Add(item);  
         
                           }  
                       }  
                   }  
               }  
         
               private async void CmdRefresh()  
               {  
                   IsRefreshing = true;  
                   await Task.Delay(3000);  
                   IsRefreshing = false;  
               }  
         
               public event PropertyChangedEventHandler PropertyChanged;  
         
               private void OnPropertyChanged(string property)  
               {  
                   if (PropertyChanged != null)  
                       PropertyChanged(this, new PropertyChangedEventArgs(property));  
               }  
           }  
       }  
    

    I edit the MainPage.xaml like following code. I just add Company Justification and OrderNumber to make a test.

       <ContentView>  
               <!-- Place new controls here -->  
               <dg:DataGrid x:Name="MyGird" ItemsSource="{Binding Professionals}" SelectionEnabled="True" RowHeight="70" HeaderHeight="50"  
                           BorderColor="#CCCCCC" HeaderBackground="#E0E6F8" PullToRefreshCommand="{Binding RefreshCommand}" IsRefreshing="{Binding IsRefreshing}" ActiveRowColor="#8899AA">  
                   <x:Arguments>  
                       <ListViewCachingStrategy>RetainElement</ListViewCachingStrategy>  
                   </x:Arguments>  
                   <dg:DataGrid.HeaderFontSize>  
                       <OnIdiom x:TypeArguments="x:Double">  
                           <OnIdiom.Tablet>15</OnIdiom.Tablet>  
                           <OnIdiom.Phone>12</OnIdiom.Phone>  
                       </OnIdiom>  
                   </dg:DataGrid.HeaderFontSize>  
                   <dg:DataGrid.Columns>  
                       <dg:DataGridColumn Title="Company" PropertyName="Company" Width="1*"></dg:DataGridColumn>  
                       <dg:DataGridColumn  Width="2*">  
                           <dg:DataGridColumn.FormattedTitle>  
                               <FormattedString>  
                                   <Span Text="Justification" TextDecorations="Underline" FontSize="13" TextColor="Black" FontAttributes="Bold">  
                                   </Span>  
                               </FormattedString>  
                           </dg:DataGridColumn.FormattedTitle>  
         
                           <dg:DataGridColumn.CellTemplate>  
                               <DataTemplate>  
                                   <Label Text="{Binding Justification}" HorizontalOptions="Center" VerticalOptions="Center"   TextColor="Blue"  
                         TextDecorations="Underline" >  
                                       <Label.GestureRecognizers>  
                                           <TapGestureRecognizer Command="{Binding Path=BindingContext.ClickCommand, Source={x:Reference Name=MyGird} }" CommandParameter="{Binding .}"/>  
                                       </Label.GestureRecognizers>  
                                         
                                   </Label>  
                               </DataTemplate>  
         
                           </dg:DataGridColumn.CellTemplate>  
                       </dg:DataGridColumn>  
                       <dg:DataGridColumn Title="OrderNumber" PropertyName="OrderNumber" Width="2*"/>  
                       <!--<dg:DataGridColumn Title="User-Agent" PropertyName="User-Agent" Width="2*"/>  
                       <dg:DataGridColumn Title="Referer" PropertyName="Referer" Width="1*"/>-->  
                   </dg:DataGrid.Columns>  
                   <dg:DataGrid.RowsBackgroundColorPalette>  
                       <dg:PaletteCollection>  
                           <Color>#F2F2F2</Color>  
                           <Color>#FFFFFF</Color>  
                       </dg:PaletteCollection>  
                   </dg:DataGrid.RowsBackgroundColorPalette>  
               </dg:DataGrid>  
           </ContentView>  
       </ContentPage>  
    

    Here is running screenshot.

    75922-image.png

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2021-03-10T08:17:18.05+00:00

    And change your GetData method of ApprovalPageViewModel the code

       using Newtonsoft.Json;  
       using System;  
       using System.Collections.Generic;  
       using System.Collections.ObjectModel;  
       using System.ComponentModel;  
       using System.Diagnostics;  
       using System.Net.Http;  
       using System.Text;  
       using System.Threading.Tasks;  
       using System.Windows.Input;  
       using Xamarin.Forms;  
       using XFDataGrid.Models;  
         
       namespace XFDataGrid.ViewModels  
       {  
           public class ApprovalPageViewModel : INotifyPropertyChanged  
           {  
               private bool _isRefreshing;  
         
               public ObservableCollection<Table> MistHeaders { get; set; }  
         
               public bool IsRefreshing  
               {  
                   get  
                   {  
                       return _isRefreshing;  
                   }  
                   set  
                   {  
                       _isRefreshing = value;  
                       OnPropertyChanged(nameof(IsRefreshing));  
                   }  
               }  
               public ICommand RefreshCommand { get; set; }  
         
               public ApprovalPageViewModel()  
               {  
                   MistHeaders = new ObservableCollection<Table>();  
         
                   GetData();  
                   RefreshCommand = new Command(CmdRefresh);  
               }  
         
               private async void GetData()  
               {  
                   string requestUrl = "https://mist.zp.co.za:6502/MIST.svc/head/M@H$@203@R"; //URL.MistHeaders;  
                   using (var client = new HttpClient())  
                   {  
                       HttpResponseMessage response = await client.GetAsync(requestUrl);  
                       try  
                       {  
                           if (response.StatusCode == System.Net.HttpStatusCode.OK)  
                           {  
                               string content = await response.Content.ReadAsStringAsync();  
                               Root root = JsonConvert.DeserializeObject<Root>(content);  
                               List<Table> mistHeaders = root.Table;  
         
                               foreach (var item in mistHeaders)  
                               {  
                                   MistHeaders.Add(item);  
                               }  
                           }  
                       }  
                       catch (Exception ex)  
                       {  
                           Debug.WriteLine("\tERROR {0}", ex.Message);  
                       }  
                   }  
               }  
         
               private async void CmdRefresh()  
               {  
                   IsRefreshing = true;  
                   await Task.Delay(3000);  
                   IsRefreshing = false;  
               }  
         
               public event PropertyChangedEventHandler PropertyChanged;  
         
               private void OnPropertyChanged(string property)  
               {  
                   if (PropertyChanged != null)  
                       PropertyChanged(this, new PropertyChangedEventArgs(property));  
               }  
           }  
       }  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.