Serialize dataGridView to JSON
Asked Answered
B

2

5

I have a datagridview on my Windows Form Application that takes input from a user. I'd like to use JSON to store this input and am trying to serialize the input from the datagridview into JSON.

So far I have:

        private void button2_Click(object sender, EventArgs e)
    {

        string output = JsonConvert.SerializeObject(this.dataGridView1);
        System.IO.File.WriteAllText("json.json", output);
    }

However something seems to be going wrong in trying to serialize the datagridview (prior I was under the impression any object could be converted?). Does this mean I have to convert the datagridview to an array or a list or something similar before I can serialize it?

Bittersweet answered 22/11, 2016 at 12:26 Comment(4)
You converting windows forms control, but you want convert data which this control presenting. For the answer you need to provide information how you inserting data in the DataGridViewCanady
@Canady As I said, the data is inserted by a user, the datagridview does not get its data elsewhere. The datagridview IS the method by which data is inserted.Bittersweet
Always serialize the data, not the view. From reading the docs it seems that DataGridView.DataSource is the object you want to serialize.Bigg
@Skynet that seems to have done the trick, feel free to add it as the solution and I'll mark it solved.Bittersweet
B
4

Always serialize the data itself and not the view.

In this case you have to serialize the DataSource property of the DataGridView.

Bigg answered 22/11, 2016 at 12:42 Comment(0)
C
4

You want convert only data, not a windows forms control.

My suggestion to create a class which represent one row of information in DataGridView

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Then create collection and assign it to the DataGridView.DataSource

public partial class YourForm : Form
{
    private readonly BindingList<Person> _data;

    public YourForm()
    {
        InitializeComponent();

        // Create empty collection/datasource
        _data = new BindingList<Person>();

        // This line will generate columns automatically if
        // DataGridView.AutoGenerateColumns = true (by default it is true)
        this.yourDataGridView.DataSource = _data;
    }
}

Which you can later serialize

private void button1_Click(object sender, EventArgs e)
{
    string output = JsonConvert.SerializeObject(_data);
    System.IO.File.WriteAllText("json.json", output);
}
Canady answered 22/11, 2016 at 12:38 Comment(0)
B
4

Always serialize the data itself and not the view.

In this case you have to serialize the DataSource property of the DataGridView.

Bigg answered 22/11, 2016 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.