添加行时DataTable中的列重复

我创建一个DataTable并将其绑定到DataGrid。 我的DataSource包含一个表(FooTable),它由一列(FooName)组成。

以下代码运行正常 – 除了每次添加新行时,都有一个重复的列填充相同的数据,我不知道如何摆脱。 见下图和代码。 我只有一个FooName列,并且出现了一个重复的列。

在此处输入图像描述

/* Create a DataGrid dg1 */ DataGrid dg1 = new DataGrid(); DataGridTextColumn col = new DataGridTextColumn(); col = new DataGridTextColumn(); colA.Binding = new Binding("FooName"); colA.Header = "FooName"; dg1.Columns.Add(colA); dataGrid1.Children.Add(dg1); /* Create a DataTable and bind it to DataGrid */ SqlCeDataAdapter da = new SqlCeDataAdapter(); string sqlStr = @"SELECT * FROM FooTable"; da.SelectCommand = new SqlCeCommand(sqlStr, conn); da.Fill(ds, "FooTable"); dt = ds.Tables["FooTable"]; DataRow newRow = dt.NewRow(); newRow["FooName"] = "Donkey"; dt.Rows.Add(newRow); dg1.ItemsSource = ds.Tables[0].DefaultView; 

尝试将AutoGenerateColumns设置为false

  dg1.AutoGenerateColumns = false 

尝试

 dg1.AutoGenerateColumns = false; 

应该为你工作。 现在,datagrid会自动生成列并添加您要求的列