C# 更改绑定到 DataGridView 的 DataTable 中的列顺序不会反映在视图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/499321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing column order in DataTable bound to DataGridView does not reflect in the view
提问by Brendan
When the application is run, the DataGridView
is bound to a DataTable
. Later I add more columns to the DataTable
programmatically and it is reflected in the underlying data - i.e. the column Ordinals are as they should be. However this is not reflected in the DataGridView
. Instead columns are appended onto the originally generated set.
当应用程序运行时,DataGridView
绑定到DataTable
. 后来我以DataTable
编程方式向其中添加了更多列,并反映在基础数据中 - 即列序号是它们应有的样子。然而,这并没有反映在DataGridView
. 而是将列附加到最初生成的集合上。
This example demonstrates,
这个例子演示了,
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public DataTable data = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.DataSource = data;
for (int i = 0; i < 5; i++)
{
this.data.Columns.Add(i.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
DataColumn foo = new DataColumn();
this.data.Columns.Add(foo);
foo.SetOrdinal(0);
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DataColumn tmpCol in this.data.Columns)
{
Console.WriteLine("{0} : {1}", tmpCol.ColumnName, tmpCol.Ordinal);
}
}
}
Button 1 generates the columns, button 2 adds a column and sets the ordinal to 0 so it should be first in the grid, button 3 displays the ordinals of the columns and shows they are how they should be in the DataTable
.
按钮 1 生成列,按钮 2 添加一列并将序数设置为 0,因此它应该在网格中的第一个,按钮 3 显示列的序数并显示它们在DataTable
.
采纳答案by Marc Gravell
That is just how DataGridView
works; with auto-generate columns enabled, extra (unmapped) columns are appended to the end. You can unbind and re-bind to fix it; set the DataSource to null and back to the table:
这就是DataGridView
工作原理;启用自动生成列后,额外的(未映射的)列会附加到末尾。您可以解除绑定并重新绑定以修复它;将 DataSource 设置为 null 并返回到表:
this.dataGridView1.DataSource = null;
this.dataGridView1.Columns.Clear();
this.dataGridView1.DataSource = data;
回答by Koryu
I had a similar problem and solved it with the DataGridViewColumn.DisplayIndex property.
我有一个类似的问题,并使用 DataGridViewColumn.DisplayIndex 属性解决了它。
dgvData.Columns["COLUMN_NAME"].DisplayIndex = 0; // will move your custom column to first position
回答by Shawn
Don't forget to turn on and off AutoColumnCreate to ensure that you'r DisplatIndex's work.
不要忘记打开和关闭 AutoColumnCreate 以确保您是 DisplatIndex 的工作。
http://www.internetworkconsulting.net/content/datadridview-displayorder-not-working
http://www.internetworkconsulting.net/content/datadridview-displayorder-not-working