The method takes as parameters the
DataTable
you want to add the column to and a
StringBuilder
representing the name of the column.
Call the method, passing it both parameters:
System.Data.DataTable dt = new DataTable();
System.Data.SqlClient.SqlCommand cmd =
new System.Data.SqlClient.SqlCommand("SELECT ColumnName FROM Foo", connString);
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
System.Text.StringBuilder name = new System.Text.StringBuilder(dr.GetString(0));
AddTableColumn(dt, name)
}
}
The method calls itself recursively, trying to add the column and appending a space each time it fails, until the column can be added to the table. Extra spaces make the name unique and avoid the
DuplicateNameException
.
private static void AddTableColumn(DataTable resultsTable, StringBuilder ColumnName)
{
try
{
DataColumn tableCol = new DataColumn(ColumnName.ToString());
resultsTable.Columns.Add(tableCol);
}
catch (System.Data.DuplicateNameException)
{
ColumnName.Append(" ");
AddTableColumn(resultsTable, ColumnName);
}
}