Add column to DataGridView (VB.NET)

2019-09-22 14:36发布

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

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

3条回答
倾城 Initia
2楼-- · 2019-09-22 15:13

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

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.

查看更多
Animai°情兽
3楼-- · 2019-09-22 15:15

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.

try to add

dgv.DataSource = Nothing

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

dgv.datasource = datatable 

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

查看更多
Anthone
4楼-- · 2019-09-22 15:26

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 IDataTable itself :

 datatable.Columns.Add("Header text", GetType(System.String)).SetOrdinal(datatable.Columns.Count)
查看更多
登录 后发表回答