0

I have a datagridview that is not bound directly do a datasource. Instead, I add the data from various methods during runtime. I created a method that accepts a dataSet and outputs it into Excel, but I can't find if there is an in-built way to geta dataSet from a dataGridView.

Thanks.

TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101
  • 1
    Why not just add your data to a DataSet instead of to the grid in the first place? Then you can just set the DataSource of the grid to the DataSet. – Chris Barlow Mar 06 '12 at 14:00
  • I could do that, but I would rather do it with the method I specified in the question. A lot less overhead. – TheGateKeeper Mar 06 '12 at 14:04
  • 1
    so why not save to excel directly from datagridview? [example](http://www.codeproject.com/Articles/32224/Exporting-a-DataGridView-to-Excel-in-NET-2-0-C-cod) – Renatas M. Mar 06 '12 at 14:09

1 Answers1

1

I updated the code to work. There was a few typos in the previous answer.

DataTable dt = new DataTable();
for (int i = 0; i < dgvPaperAndPlastic.Columns.Count; i++)
{
     DataColumn column = new DataColumn(dgvPaperAndPlastic.Columns[i].HeaderText);
     dt.Columns.Add(column);
}
int noOfColumns = dgvPaperAndPlastic.Columns.Count;
foreach (DataGridViewRow dr in dgvPaperAndPlastic.Rows)
{
     //Create table and insert into cell value.
     DataRow dataRow = dt.NewRow();

     for (int i = 0; i < noOfColumns; i++)
     {
          dataRow[i] = dr.Cells[i].Value.ToString();
     }
}
Picrofo Software
  • 5,475
  • 3
  • 23
  • 37