Click here to Skip to main content
15,887,301 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
Could anyone please help me with converting my datagrisview to datatable type.

I use this code to retrive the datagrid value, but it only returns NULL....

DataTable dt = new DataTable();
dt = dataGridViewSql.DataSource as DataTable;

I have read something about using "viewstate", bu i dont realy understand how..

I would be realy greatfull any answer!

//mlm
Posted
Comments
Kenneth Haugland 23-Oct-13 17:19pm    
WinForm or WPF?
In WPF all you woul dhave to do to show a DataTable is to call:
DataGridViewSQL.ItemsSource = dt.DefaultView

1 solution

C#
public DataTable DataGridView2DataTable(DataGridView dgv, String tblName, int minRow=0)
{
  DataTable dt = new DataTable(tblName);
        
  // Header columns
  foreach (DataGridViewColumn column in dgv.Columns)
  {
    DataColumn dc = new DataColumn(column.Name.ToString());
    dt.Columns.Add(dc);
  }

  // Data cells
  for (int i = 0; i < dgv.Rows.Count; i++)
  {
    DataGridViewRow row = dgv.Rows[i];
    DataRow dr = dt.NewRow();
    for (int j = 0; j < dgv.Columns.Count; j++)
    {
      dr[j] = (row.Cells[j].Value == null) ? "" : row.Cells[j].Value.ToString();
    }
    dt.Rows.Add(dr);
  }

  // Related to the bug arround min size when using ExcelLibrary for export
  for (int i = dgv.Rows.Count; i < minRow; i++)
  {
    DataRow dr = dt.NewRow();
    for (int j = 0; j < dt.Columns.Count; j++)
    {
      dr[j] = "  ";
    }
    dt.Rows.Add(dr);
  }
  return dt;
}


from:
http://www.maslik.com/how-to-convert-datagridview-to-datatable-using-csharp[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900