简体   繁体   中英

Populate WPF DataGrid With JSON Data in C# using RestSharp

I would tell you I am relatively new to all of this, but it will probably be obvious shortly. I have been researching for two days without any luck in finding my specific question answered so here is what I am trying to do:

In the MainWindow code behind of a WPF app I have this class:

public class LocaleInfo
    {

        public string id { get; set; }
        public string category { get; set; }
        public bool jobSite { get; set; }
        public bool singleJob { get; set; }
        public bool useMasterPack { get; set; }
        public string maxAllowed { get; set; }

    }

Which I add a list to in order to handle JSON data coming from a web service formatted as an array. (Comments added to help you understand my line of thinking and maybe shed light on why I built each line like I did - hope it helps!)

public List<LocaleInfo> LocaleList;  

I then have the following code to get the JSON data:

var client = new RestClient("https://webservice info"); // Create Rest Client
var request = new RestRequest(Method.GET);  //Create Rest Request
request.RequestFormat = RestSharp.DataFormat.Json; // Request JSON to ensure accuracy 
request.AddHeader("Authorization", "tokenxxx");  // Add header item Authorization and Token

var response = client.Execute(request);  // Execute the Request

JsonDeserializer deserial = new JsonDeserializer();  // Create JSON Deserializer object
LocaleList = deserial.Deserialize<List<LocaleInfo>>(response);  // Deserialize JSON Receieved from API/WEbservice into List<class>

Int32 totalCount = LocaleList.Count;  // Create variable and get total record count

txtCount.Text = totalCount.ToString();  // Show record count

I believe it populates the list as I get a proper count.

On the MainWindow.xaml I have placed a DataGrid with 6 columns with headers. What I cannot seem to find or figure out is how to link or iterate through the list to add the data into the DataGrid.

Someday I will look back on this post and probably shake my head, but this is where I am at and I could really use some help.

Thanks so much in advance!

Add this in your MainWindow's Constructor :

DataContext = this;

then use ObservableCollection instead of List :

Public ObservableCollection<LocalInfo> LocalList{get; set;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM