ADO.NET - 删除先前已重命名的列时的DataTable /问题

时间:2014-05-23 16:34:01

标签: datatable ado.net

我尝试从DataTable中删除列时遇到问题,此时此列已经创建并从同一个DataTable重命名。

这是代码片段。我正在使用.NET Frameword 4.5。

重现起来非常简单。

try
{
    DataTable data = new DataTable();
    data.CaseSensitive = false;

    data.Columns.Add("column1", typeof(string));
    data.Columns.Add("column2", typeof(string));
    data.Columns.Add("column3", typeof(string));

    DataRow newRow = data.NewRow();
    newRow["column1"] = "AAAAA";
    newRow["column2"] = "BBBBB";
    newRow["column3"] = "CCCCC";
    data.Rows.Add(newRow);

    data.AcceptChanges();

    // Rename first column
    Console.WriteLine("Rename [column1] to [COLUMN1] ...");
    data.Columns["column1"].ColumnName = "COLUMN1";
    data.AcceptChanges();

    // Delete Column
    Console.WriteLine("Delete column [column1] ...");
    if (data.Columns.Contains("column1"))
    {
        data.Columns.Remove("column1");
        data.AcceptChanges();
        // Somehow the column will still partially exists after the 2 above lines
        // If you look at the DataTable, it is gone, but if you test existance of the column, it will still think it is there
        if (data.Columns.Contains("column1"))
        {
            Console.WriteLine("[column1] still Exists! WHY?");
        }
    }

    // Then i need to Recreate that same column ... of course it will fail
    Console.WriteLine("Recreate column [column1] ...");
    data.Columns.Add("column1", typeof(string)); 
    // this throw Exception as the data seems to still somehow exists in the DataTable
}
catch (Exception ex)
{
    Console.WriteLine("Error=" + ex.Message);
}
finally
{
    Console.WriteLine("Press any key to exit!");
    Console.ReadLine();
}

我几乎在所有地方都添加了AcceptChanges调用,以查看它是否有所作为,但没有差异。

有什么想法吗? 我做错了吗?

提前感谢您的任何意见/帮助

0 个答案:

没有答案