Skip to content

Instantly share code, notes, and snippets.

@jdowd7
Created August 14, 2015 14:07
Show Gist options
  • Save jdowd7/54630d4f48da1fce958e to your computer and use it in GitHub Desktop.
Save jdowd7/54630d4f48da1fce958e to your computer and use it in GitHub Desktop.
Enforces null columns to prevent getting dropped when serializing
private static void datatableEnforceNulls(DataTable resultTable)
{
List<string> removeList = new List<string>();
foreach (DataColumn column in resultTable.Columns)
{
if (resultTable.Rows.OfType<DataRow>().All(r => r.IsNull(column)))
{
if (column.DataType != typeof(String))
{
removeList.Add(column.ColumnName);
}
if (column.DataType == typeof(String))
{
column.DefaultValue = "";
}
}
}
foreach (string col2Remove in removeList)
{
resultTable.Columns.Remove(col2Remove);
resultTable.Columns.Add(col2Remove);
resultTable.Columns[col2Remove].DefaultValue = "";
}
int i, j;
for (i = 0; i < resultTable.Columns.Count; i++)
{
for (j = 0; j < resultTable.Rows.Count; j++)
{
if (resultTable.Columns[i].DataType.ToString() == "System.String")
{
if (resultTable.Rows[j][i] == DBNull.Value || resultTable.Rows[j][i].ToString().Trim() == "")
resultTable.Rows[j][i] = "";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment