user2417731 user2417731 - 5 days ago 5
Vb.net Question

DataGridView not getting columns from DataTable when binding

I have a

DataGridView
that I am binding to a table. After I do the following code:

Dim filterTable As New DataTable
filterTable.Columns.Add("KeyName")
filterTable.Columns.Add("Path")

GridView.DataSource = filterTable

GridView.Columns.Count remains 0.


Basically, the
BindUnidentifiedKeys(UnidentifiedKeys As Dictionary(Of String, String), ByRef GridView As DataGridView)
is called.

I call it like this:
UnidentifiedKeysManager.Instance.BindUnidentifiedKeys(UnidentifiedKeysManager.Instance.GetKeys, grdUnidentifiedKeys)


I pass it a dictionary and a
DataGridView
, by reference.

Yet when I set it's datasource to a datatable that has columns, the
GridView
's columns remain
0
. I don't know why this is happening.

Answer

When binding to a DataGridView, take note of the property AutoGenerateColumns. If you set this property to True when you bind the data table to the DataGridView, it will generate columns based on the columns as defined in the data table, which may be what you're after:

Dim filterTable As New DataTable
filterTable.Columns.Add("KeyName")
filterTable.Columns.Add("Path")

GridView.AutoGenerateColumns = True
GridView.DataSource = filterTable

Alternatively, you can go in the designer and create your columns in the DataGridView manually. When doing this for bound gridviews, set each column's DataPropertyName property which will bind the gridview column to the corresponding column/field in the data table (make sure to preserve column order in both). In this case, you'd want to NOT auto generate columns. You can also do this programmatically.

Comments