C# DataTable包含一个不存在于c中的列
我一直在尝试重置数据表,以便用户可以加载另一个xml文件。 尽管我不断得到重复名称异常,即使datatable没有任何列附加到它 代码片段示例C# DataTable包含一个不存在于c中的列,c#,datatable,C#,Datatable,我一直在尝试重置数据表,以便用户可以加载另一个xml文件。 尽管我不断得到重复名称异常,即使datatable没有任何列附加到它 代码片段示例 string rdr = (Path.ChangeExtension(filepath, ".xsd")); ds.ReadXmlSchema(rdr); ds.ReadXml(xmlFile); resetDataTable(dt); Console.WriteLine(dt.Columns.Count);//This gives 0 foreach
string rdr = (Path.ChangeExtension(filepath, ".xsd"));
ds.ReadXmlSchema(rdr);
ds.ReadXml(xmlFile);
resetDataTable(dt);
Console.WriteLine(dt.Columns.Count);//This gives 0
foreach (DataColumn c in ds.Tables[1].Columns)//ds.Tables[1] is the sheet that the data is on,
//it's probably due to how the xml are laid out. They're created out of a script, so they always follow the
//same rules
{
if(dt.Columns.Contains(c.ColumnName)){
//It enters here even though it has no columns
dt.Columns.Remove(c.ColumnName);
//ArgumentException trying to delete a column that doesn't
//belong to the datatable
}
dt.Columns.Add(c.ColumnName);
//Will crash here normaly saying the column already exists.
}
private void resetDataTable(DataTable dt){
dt.Columns.Clear();
dt.Clear();
}
你在比较苹果和橙子,dt是一个数据表,ds.表[1]可能是另一个。旁注:第一个表是ds.Tables[0]。不是重置…而是创建一个新引用?!从xml加载时,它将数据放在ds.Tables[1]表中,我将这些数据加载到我的dataTable中,通常它可能位于ds.Tables[0]上,但输入的xml将其放在第二张表中。关于创建一个新的引用,我会很快重试,我以前做过,后来在中它被取消引用时会导致问题。为了回答这个问题,我们需要看看dt是如何分配的。正如@TimSchmelter指出的,它可能是一个与ds.Tables不同的对象引用[1]