Search code examples
ado.netdatagridviewdatagridviewcolumn

How to copy DataGridView contents to Dataset?


i'm not good with ADO.NET so used the following code that i got from Internet but i get the error "There is no row at position 0." @ the marked line(*) even though i can see a value is being passed using breakpoints

        DataSet ds = new DataSet();
        DataTable dt = new DataTable("ProdFromDGV");
        ds.Tables.Add(dt);
        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {
            dt.Columns.Add(col.HeaderText, typeof(string));
        }

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                *dt.Rows[row.Index][cell.ColumnIndex] = cell.Value.ToString();*
            }
        }
        dt.WriteXml("table.xml");

Solution

  • You need to first create a DataRow type and add it into your DataTable before you can start assigning to it.

    So your code will now be something like:

    DataSet ds = new DataSet();
    DataTable dt = new DataTable("ProdFromDGV");
    ds.Tables.Add(dt);
    
    foreach (DataGridViewColumn col in dataGridView1.Columns)
    {
        dt.Columns.Add(col.HeaderText, typeof(string));
    }
    
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
             // This will not work, but it's something similar to this that you need here...
             DataRow row = new DataRow();
             dt.RowCollecion.Add(row);    
    
             // Now you can assign to the row....
             dt.Rows[row.Index][cell.ColumnIndex] = cell.Value.ToString();
         }
    }
    
    dt.WriteXml("table.xml");
    

    Hope this helps some..