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?

bucketman
  • 463
  • 6
  • 15
  • 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 `DataGridView` – Fabio Nov 22 '16 at 12:29
  • @Fabio 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. – bucketman Nov 22 '16 at 12:32
  • Always serialize the data, not the view. From reading the docs it seems that DataGridView.DataSource is the object you want to serialize. – sknt Nov 22 '16 at 12:36
  • @Skynet that seems to have done the trick, feel free to add it as the solution and I'll mark it solved. – bucketman Nov 22 '16 at 12:38

2 Answers2

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);
}
Fabio
  • 31,528
  • 4
  • 33
  • 72
4

Always serialize the data itself and not the view.

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

sknt
  • 963
  • 6
  • 16