Created
August 14, 2015 14:07
-
-
Save jdowd7/54630d4f48da1fce958e to your computer and use it in GitHub Desktop.
Enforces null columns to prevent getting dropped when serializing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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