DataGridView To Datatable in C#

public DataTable DataGridView2DataTable(DataGridView dgv, String tblName, int minRow=0)//Simply Use this Function For Conversion it would return Datatble
{

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;

}

Posts Tagged with…

Write a Comment

Your email address will not be published. Required fields are marked *