Click here to Skip to main content
16,016,623 members
Articles / Web Development / ASP.NET
Tip/Trick

DuplicateNameException when adding columns to a DataTable dynamically

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
24 Jun 2011CPOL 26.7K   1
When building an ADO.NET DataTable dynamically in your code, each column name must be unique or you get a System.Data.DuplicateNameException. If you don't know at design time that the columns you will be adding are certain to have unique names, you can use this method to avoid a runtime error.
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.

C#
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);
            }
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to manage Datarow in Duplicate Contain Column in DataTable Pin
Rakesh Jogani17-Jan-14 20:30
professionalRakesh Jogani17-Jan-14 20:30 
Hello David

I add Duplicate datacolumn in Datatable but when i add datarow with duplicate column value
How i manage actually currently i face proble iwhen i assign data to data Row by column wise

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.