Francis
Francis

Reputation: 343

C# JSON.net populate DataGridView

I want to populate a datagridview (dgvNachrichten).

It has two columns ("Datum" and "Nachrichten").

This is my code:

try
{
    WebClient webClient = new WebClient();
    webClient.DownloadFile(Config.URL_MAIN, @Environment.GetEnvironmentVariable("TEMP") + "\\" + "temp.json");
    StreamReader sr = new StreamReader(@Environment.GetEnvironmentVariable("TEMP") + "\\" + "temp.json");
    string line = sr.ReadToEnd();
    var response = line;

    var des = (MyClass)JsonConvert.DeserializeObject(response, typeof(MyClass));
    dgvNachrichten.DataSource = des;
}
catch (Exception ex)
{

    MessageBox.Show(ex.ToString());
}

My JSON looks like this:

{ "nachrichten": [ { "Nachricht": "text", "Datum": "datum" }, { "Nachricht": "text", "Datum": "datum" }, { "Nachricht": "text", "Datum": "datum" }, { "Nachricht": "text", "Datum": "datum" } ] }

And here are my Classes:

public class MyClass
{
    public List<Nachrichten_Felder> data { get; set; }
}
public class Nachrichten_Felder
{
    public string Datum { get; set; }
    public string Nachricht { get; set; }
}

The download works fine, and after a few seconds the form with the GridView appears, but without content... The pieces with "Datum" in my JSON have to appear in the "Datum" Column (for every Datum a new row) and the same for "Nachrichten".

Maybe someone could help me out?

Upvotes: 0

Views: 381

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14241

You must map data property to value in json file:

public class MyClass
{
    [JsonProperty("nachrichten")]
    public List<Nachrichten_Felder> data { get; set; }
}

Also bind DataGridView to collection:

dgvNachrichten.DataSource = des.data;

Don't forget dispose WebClient and StreamReader.

Upvotes: 1

Related Questions