DataGridView convert to datatable

0
0

Hi

When I convert a datagridview to data table , iis memory  uses high memory and takes long time to get it back as dispose, is there a way to convert it without making the memory too big?

Thanks

public DataTable GetContentAsDataTable(DataGridView dataGridView)
{
bool IgnoreHideColumns = false;

if (dataGridView.ColumnCount == 0) return null;

using (DataTable dtSource = new DataTable(“DataTable”))
{
dtSource.TableName = “DataTable”;
foreach (DataGridViewColumn col in dataGridView.Columns)
{
if (col.Visible)
{
try
{

if (IgnoreHideColumns & !col.Visible) continue;
if (col.Name == string.Empty) continue;
if (col.ValueType == typeof(Boolean))
{
dtSource.Columns.Add(col.Name, typeof(Boolean));
}

else if (col.CellType.Name == “DataGridViewImageCell”)
{

}

else
{
dtSource.Columns.Add(col.Name, typeof(string));
}

dtSource.Columns[col.Name].Caption = col.HeaderText;
}
catch (Exception)
{
}
}
}
if (dtSource.Columns.Count == 0) return null;
foreach (DataGridViewRow row in dataGridView.Rows)
{

try
{
if (row.Visible == true)
{
DataRow drNewRow = dtSource.NewRow();
foreach (DataColumn col in dtSource.Columns)
{
if (col.DataType == typeof(Boolean) && row.Cells[col.ColumnName].Value == null)
{
row.Cells[col.ColumnName].Value = false;
}
else
{
drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
}

}
dtSource.Rows.Add(drNewRow);
}

}
catch (Exception)
{
}
}

return dtSource;
}
}

  • You must to post comments
0
0

Iterating the rows in a data bound DGV causes the virtual rows to be created increasing the memory usage by a lot.

Use dataGrid.GetValue(col, row) instead. It returns the data bound cell value without creating the row and the cells.

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.