Add column to DataGridView (VB.NET)

[亡魂溺海] 提交于 2019-12-14 03:28:53

问题


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?


回答1:


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)



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/49882487/add-column-to-datagridview-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!