0

I have some DataGridViews on a form, and would like to get a XML string from it. But for some reason it gives "Exception thrown: 'System.NullReferenceException'" at the point of return. When I look inside the foreach rows, it has the data I have put in. What is the problem here?

    public string DataGridViewToXML(DataGridView DGV)
    {
        DataTable DT = new DataTable();
        foreach (DataGridViewColumn col in DGV.Columns) { DT.Columns.Add(col.Name); }
        foreach (DataGridViewRow row in DGV.Rows)
        {
            DataRow dRow = DT.NewRow();
            foreach (DataGridViewCell cell in row.Cells) { dRow[cell.ColumnIndex] = cell.Value; }
            DT.Rows.Add(dRow);
        }
        return DT.DataSet.GetXml();
    }
Sander
  • 37
  • 5
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Mohit S May 18 '18 at 09:00
  • There is no DataSet for your DataTable `DT`. – Filburt May 18 '18 at 09:05
  • Ok clear, so the way I populate the DataTable doens't create a DataSet. I've searched on the internet, still no solution to just save the data the user puts in the DataGridView, could not be so hard? – Sander May 18 '18 at 09:24

1 Answers1

0

You haven't told as at what line it trows it but as i get it you copy all data from DGV to DT so you can parse DataSet.GetXml();?

If that is the case why you just do not do:

public string DataGridViewToXML(DataGridView DGV)
{
    return (DGV.DataSource as DataTable).DataSet.GetXml();
}

I know it doesn't solve your null error but why would you solve it when you have easier way of doing you command. Other way tell me at what line error drops and i will try explaining why it happens.

Aleksa Ristic
  • 2,394
  • 3
  • 23
  • 54