Fill GRID with JSON - Deserialized (Metrogrid - Metroframework)

Asked

Viewed 94 times

0

I’m probably doing something wrong, and I must have made a mistake doing the loop, but come on.

I have a class called 'Class.Cs' that has the following code:

 [JsonProperty("A")]
 public string A{ get; set; }

 [JsonProperty("B")]
 public string B{ get; set; }

 [JsonProperty("C")]
 public string C{ get; set; }

I did it this way, because of the JSON returns. So, when it comes to deserialize, I only inform the class and the object of the Array.

However, I need to play this on a GRID that has columns with different Class names. Ex.: First Column -> Data A that must receive the value A {get; set;}

To be more exact, the component is the Metrogrid of the Metroframework. If necessary, I can change it to Datagridview (Visual Studio Tools itself)

I had tried to make a loop, informing each item of the List<>, for the name of the Column, however, it informs me that it is not possible to do this process.

If I use the code below:

mtrgrdDataGrid.DataSource = JsonConvert.DeserializeObject<List<Classe>>(strDados);

It fills the Datagrid according to the object column.

How to fill this Datagrid, however, with custom names in the columns?

1 answer

0


You have several options:

Generating the columns automatically, you will need to inform which name will be displayed:

public class MyClas
{
    [DisplayName("Dados A")]
    public string A { get; set; }
    [DisplayName("Dados B")]
    public string B { get; set; }
    [DisplayName("Dados B")]
    public string C { get; set; }
}

Or, if they are simple names, you can simply rename the property and use Jsonproperty as you did, to map the json:

public class MyClas
{
    [JsonProperty("A")]
    public string DadosA { get; set; }
    [JsonProperty("B")]
    public string DadosB { get; set; }
    [JsonProperty("C")]
    public string DadosC { get; set; }
}

ps. You can still use both annotations together:

[JsonProperty("A")]
[DisplayName("Dados A")]
public string DadosA { get; set; }

Or, by adding the columns manually, you can define which Header Text and which Property will display:

inserir a descrição da imagem aqui

ps. Remember to disable the AutoGenerateColumns after the InitializeComponent:

dataGridView1.AutoGenerateColumns = false;
  • I ended up choosing to use the last option. I switched the component to Datagridview, and did just that from there. And voila, it fell like a glove.

  • do not forget to mark as response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.