问题
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