Search code examples
c#datatable

C# DataTable Add Column DuplicateNameException


I'm trying to add a column to a datatable within a dataset in C# (the dataset is read from an XML document). It seems that, if I name the column, I receive a DuplicateNameException when trying to add it. If I leave the column unnamed, it gets added to the datatable. It doesn't seem to matter what the name of the column actually is; just whether the Datatable.ColumnName property is defined.

Here is the relevant code block (xR is a previously defined XmlTextReader, and this is all in a while xR.Read() loop):

xR.ReadToDescendant(this.calDataTag);
XmlReader xS = xR.ReadSubtree();
ds.ReadXml(xS);

foreach (DataTable dt in ds.Tables)
{
   if (dt.Columns.Contains("offset"))
   {
      if (dt.TableName == "Single")
      {
         DataColumn c1 = new DataColumn();
         c1.Caption = "TipType";
         c1.ColumnName = "whatever";
         dt.Columns.Add(c1);
      }

      foreach (DataRow dr in dt.Rows)
      {
         foreach (DataColumn dc in dt.Columns)
         {
            outString.Add("Table: " + dt.TableName.ToString() + " Column: " + dc.ColumnName.ToString() + " RowVal: " + dr[dc] + " " + dt.Columns.Contains("whatever")); 
         }
      }
    }
 }

Interestingly, the dt.Columns.Contains("whatever") part of the string always returns False. So this is not a true DuplicateNameException. I'm sure I'm just implementing the Columns.Add method improperly. Any advice is appreciated.


Solution

  • seems to me you are checking the wrong conditions or at least you are not covering yourself enough, instead of doing this:

    if (dt.Columns.Contains("offset"))
       {
          if (dt.TableName == "Single")
    

    why don't do:

    if (dt.TableName == "Single" && !dt.Columns.Contains("whatever") && dt.Columns.Contains("offset"))
    {
      var c1 = new DataColumn();
      c1.Caption = "TipType";
      c1.ColumnName = "whatever";
      dt.Columns.Add(c1);
    }
    

    then you have to put your outString generation wherever it fits, this code should at least be easier to debug and you can find what is going on quicker.