将列添加到 DataGridView (VB.NET)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49882487/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:23:56  来源:igfitidea点击:

Add column to DataGridView (VB.NET)

vb.netdatagridviewadd

提问by F.C. Hsiao

I would like to add a new column in my project, but a weird thing happened...

我想在我的项目中添加一个新列,但是发生了一件奇怪的事情......

My code

我的代码

adapter.fill(datatable)
dgv.datasource = datatable
dgv.columns.add("test","testHeader")

The column index of test column should be the last index. However, I found the column index is 0 and the original 0th index turns to 1

测试列的列索引应该是最后一个索引。但是,我发现列索引为 0,而原来的第 0 个索引变为 1

I am not sure what happened. Is there any factor could cause this problem? property settings of datagridview is wrong?

我不确定发生了什么。是否有任何因素可能导致此问题?datagridview的属性设置有误?

回答by Aousaf rashid

It's simple , get the total column count first and then add the column at the end :

很简单,先获取总列数,然后在最后添加列:

  Dim col as New DataGridViewColumn
  col.HeaderText = "abc"

  dgv.Columns.Insert(dgv.ColumnCount, col)

If the above code doesn't help , try adding column to the IDataTableitself :

如果上面的代码没有帮助,请尝试向其IDataTable本身添加列:

 datatable.Columns.Add("Header text", GetType(System.String)).SetOrdinal(datatable.Columns.Count)

回答by PANDA MAN

Your code

你的代码

adapter.fill(datatable)
dgv.datasource = datatable
dgv.columns.add("test","testHeader")

seems to be working properly. I guess you are re-filling the datagridview that's why the added column is in index 0.

似乎工作正常。我猜您正在重新填充 datagridview,这就是为什么添加的列在索引 0 中的原因。

try to add

尝试添加

dgv.DataSource = Nothing

you will notice that the added column "test","testHeader" will be in index 0. setting again

您会注意到添加的列“test”,“testHeader”将在索引 0 中。再次设置

dgv.datasource = datatable 

will cause the added column to remain at index 0 while the datatable will be added to the succeeding columns.

将导致添加的列保留在索引 0,而数据表将添加到后续列。

回答by PavlinII

There's a DataGridViewColumn.DisplayedIndexproperty to control order of visible columns.

有一个DataGridViewColumn.DisplayedIndex属性来控制可见列的顺序。

Keep in mind that DataGridView tracks theese values and update them for other columns in your grid. Chaning some of them to 0 will update all other columns to highter values.

请记住,DataGridView 会跟踪这些值并为网格中的其他列更新它们。将其中一些更改为 0 会将所有其他列更新为更高的值。