Share via


A column named 'col1' already belongs to this DataTable

Question

Friday, April 16, 2010 5:42 PM

I developed a C#/SQL Server 2008 (Full Installation, not Express) web application using VS 2008.  This application works great in VS.  And now it works in IE also.  But the problem is that I have to restart IIS each time after running this web application one time.  So the problem must be that the DataTable is not getting cleared between application runs.  How can I resolve this error?

How I'm fixing this right now is I restart IIS service after each application run.  Here are the details of my error:

<title>A column named 'col1' already belongs to this DataTable.</title> <mce:style><!-- body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } --></mce:style><style mce_bogus="1"><!-- body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } --></style>

Server Error in '/AddFileToSQL' Application.


A column named 'col1' already belongs to this DataTable.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.DuplicateNameException: A column named 'col1' already belongs to this DataTable.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[DuplicateNameException: A column named 'col1' already belongs to this DataTable.]
   System.Data.DataColumnCollection.RegisterColumnName(String name, DataColumn column, DataTable table) +4828257
   System.Data.DataColumnCollection.BaseAdd(DataColumn column) +93
   System.Data.DataColumnCollection.AddAt(Int32 index, DataColumn column) +78
   System.Data.DataColumnCollection.Add(DataColumn column) +8
   AddFileToSQL.DataMatch.PopulateFileInputTable() in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\DataMatch.aspx.cs:112
   AddFileToSQL.DataMatch.CreateChildControls() in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\DataMatch.aspx.cs:289
   System.Web.UI.Control.EnsureChildControls() +87
   System.Web.UI.Control.PreRenderRecursiveInternal() +44
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842

All replies (4)

Saturday, April 17, 2010 5:34 PM âś…Answered

Yes, this does help.  Before I ran it this time I checked for Security Updates for IE and after downloading MS10-018, I am now getting an exception in VS when I try to run this same application.  The exception occurs on the line in my Default.aspx.cs file:

if (uploadFile.PostedFile.ContentLength > 0)
            {

                inputfile = System.IO.File.ReadAllText(path);
                Session["Message"] = inputfile;
                Response.Redirect("DataMatch.aspx");
            }

And the details of this exception are below.  I will try to google the solution to this, but if you are able to determine the cause meanwhile, that would be super!

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Word.Document"><meta name="Generator" content="Microsoft Word 11"><meta name="Originator" content="Microsoft Word 11"><link rel="File-List" href="file:///C:%5CDOCUME%7E1%5CAdmin%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml"><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><style> <!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --> </style><!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} </style> <![endif]-->

System.NotSupportedException was unhandled by user code<o:p></o:p>

  Message="The given path's format is not supported."<o:p></o:p>

  Source="mscorlib"<o:p></o:p>

  StackTrace:<o:p></o:p>

       at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)<o:p></o:p>

       at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)<o:p></o:p>

       at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)<o:p></o:p>

       at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)<o:p></o:p>

       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)<o:p></o:p>

       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)<o:p></o:p>

       at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)<o:p></o:p>

       at System.IO.StreamReader..ctor(String path, Encoding encoding)<o:p></o:p>

       at System.IO.File.ReadAllText(String path, Encoding encoding)<o:p></o:p>

       at System.IO.File.ReadAllText(String path)<o:p></o:p>

       at AddFileToSQL._Default.btnAppend_Click(Object sender, EventArgs e) in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\Default.aspx.cs:line 107<o:p></o:p>

       at System.Web.UI.HtmlControls.HtmlInputButton.OnServerClick(EventArgs e)<o:p></o:p>

       at System.Web.UI.HtmlControls.HtmlInputButton.RaisePostBackEvent(String eventArgument)<o:p></o:p>

       at System.Web.UI.HtmlControls.HtmlInputButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)<o:p></o:p>

       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)<o:p></o:p>

       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)<o:p></o:p>

       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)<o:p></o:p>

  InnerException:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Word.Document"><meta name="Generator" content="Microsoft Word 11"><meta name="Originator" content="Microsoft Word 11"><link rel="File-List" href="file:///C:%5CDOCUME%7E1%5CAdmin%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml" mce_href="file:///C:%5CDOCUME%7E1%5CAdmin%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml"><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><mce:style><!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --></mce:style><style mce_bogus="1"><!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --></style><!--[if gte mso 10]> <mce:style><!-- /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --></mce:style><style mce_bogus="1"><!-- /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --></style> <![endif]-->

System.NotSupportedException was unhandled by user code<o:p></o:p>

  Message="The given path's format is not supported."<o:p></o:p>

  Source="mscorlib"<o:p></o:p>

  StackTrace:<o:p></o:p>

       at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)<o:p></o:p>

       at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)<o:p></o:p>

       at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)<o:p></o:p>

       at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)<o:p></o:p>

       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)<o:p></o:p>

       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)<o:p></o:p>

       at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)<o:p></o:p>

       at System.IO.StreamReader..ctor(String path, Encoding encoding)<o:p></o:p>

       at System.IO.File.ReadAllText(String path, Encoding encoding)<o:p></o:p>

       at System.IO.File.ReadAllText(String path)<o:p></o:p>

       at AddFileToSQL._Default.btnAppend_Click(Object sender, EventArgs e) in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\Default.aspx.cs:line 107<o:p></o:p>

       at System.Web.UI.HtmlControls.HtmlInputButton.OnServerClick(EventArgs e)<o:p></o:p>

       at System.Web.UI.HtmlControls.HtmlInputButton.RaisePostBackEvent(String eventArgument)<o:p></o:p>

       at System.Web.UI.HtmlControls.HtmlInputButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)<o:p></o:p>

       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)<o:p></o:p>

       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)<o:p></o:p>

       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)<o:p></o:p>

  InnerException:


Saturday, April 17, 2010 2:20 AM

what's the code in

   C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\DataMatch.aspx.cs row 112 ?
   C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\DataMatch.aspx.cs row 289 ?

Saturday, April 17, 2010 11:17 AM

Thank you!  Here is the code with lines 112 and 289 identified below.  I'm giving you all of the context lines also.

// This data comes from input file
        private void PopulateFileInputTable()
        {
            myInputFile.Clear();
            string strInput, newrow;
            string[] oneRow;
            DataColumn myDataColumn;
            DataRow myDataRow;
            int result, numRows;

            //Read the input file
            strInput = Session["Message"].ToString();
            data = strInput.Split('\r');

            //Headers
            headers = data[0].Split('|');

            //Data
            for (int i = 0; i < data.Length; i++)
            {
                newrow = data[i].TrimStart('\n');
                data[i] = newrow;
            }
            result = String.Compare(data[data.Length - 1], "");
            numRows = data.Length;

            if (result == 0)
            { numRows = numRows - 1; }

            data2 = new string[numRows];

            for (int a = 0, b = 0; a < numRows; a++, b++)
            {
                data2[b] = data[a];
            }

            // Create columns
            for (int col = 0; col < headers.Length; col++)
            {
                @temp = (col + 1);
                @tempS = @temp.ToString();
                @tempT = "@col"+ @temp.ToString();

                myDataColumn = new DataColumn();
                myDataColumn.DataType = Type.GetType("System.String");
                myDataColumn.ColumnName = headers[col];

//LINE 112 IS THIS LINE BELOW!
                myInputFile.Columns.Add(myDataColumn);
                ddl_ht.Add(@tempT, headers[col]);
            }

            // Create new DataRow objects and add to DataTable.    
            for (int r = 0; r < numRows - 1; r++)
            {
                oneRow = data2[r + 1].Split('|');
                myDataRow = myInputFile.NewRow();
                for (int c = 0; c < headers.Length; c++)
                {
                    myDataRow[c] = oneRow[c];
                }
                myInputFile.Rows.Add(myDataRow);
            }
            NumberOfControls = headers.Length;
            myUserSelections = new string[NumberOfControls];
        }

        //Create display panel
        private void CreateDisplayPanel()
        {
            btnSubmit.Style.Add("top", "auto");
            btnSubmit.Style.Add("left", "auto");
            btnSubmit.Style.Add("position", "absolute");
            btnSubmit.Style.Add("top", "200px");
            btnSubmit.Style.Add("left", "400px");

            newcol = CreateDropDownLists();

            for (int counter = 0; counter < NumberOfControls; counter++)
            {
                pnlDisplayData.Controls.Add(newcol[counter]);
                pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
                pnlDisplayData.Visible = true;
                pnlDisplayData.FindControl(newcol[counter].ID);
            }
        }

        // Create TextBoxes and DropDownList data here on postback.
        protected override void CreateChildControls()
        {
            // create the child controls if the server control does not contains child controls
            this.EnsureChildControls();

            // Creates a new ControlCollection.
            this.CreateControlCollection();

            // Here we are recreating controls to persist the ViewState on every post back
            if (Page.IsPostBack)
            {
                RecreateDisplayPanel();
                RecreateLabels();
            }
            // Create these conrols when asp.net page is created
            else
            {

//THIS IS LINE 289 BELOW!

               PopulateFileInputTable();
                CreateDisplayPanel();
                CreateLabels();
            }

            // Prevent dropdownlists and labels from being created again.
            if (restart == false)
            {
                this.ChildControlsCreated = true;
            }
            else if (restart == true)
            {
                this.ChildControlsCreated = false;
            }
        }


Saturday, April 17, 2010 11:44 AM

Hi,

You call myInputFile.Clear().  If this is a DataTable that already has columns defined for it, then this Cear() method does not remove the columncollection.  Is this your problem?  Does your line 112 add a column that has already been added to the column collection of the DataTable?  You might try myInputFile.Columns.Clear() or some other method of  removing columns before adding them.  Perhaps you should test whether a particular column exists in the collection before adding it.

For what it's worth.., I hope it helps.