Search code examples
c#jsonserializationdatagridviewjsonserializer

Serialize dataGridView to JSON


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?


Solution

  • Always serialize the data itself and not the view.

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