Sultanen Sultanen - 10 months ago 56 Question

VB.NET - Adding columns to DataGridView's in a list

I have a program where i let the user dynamically add DataGridViews to the interface, those are also added to a list for easy management. All of the DataGridViews have their own datasources. I am using a Databinding source to get different DataGridViewTextBoxColumns to add.

The problem is the following:
When the user adds the first table the following code runs:

dataGridList(dataGridList.Count -1).Clear()
dataGridList(dataGridList.Count -1).Add(NameDataGridViewTextBoxColumn)

No problem there and the right data is displayed, but when the user adds the second table i get an exception thrown:

"Provided column already belongs to the datagrid view"

I think this is strange since i access different DataGridView's right?

The point of all of this is to be able to view different columns in all the DataGridViews depending on the users choices.

Hope you can help me.

Jay Jay
Answer Source

How are you determining what NameDataGridViewTextBoxColumn is? What I mean is how is your list of textBoxColumns you mentioned created?

It seems likely that you actually need to create a New DataGridViewTextBoxColumn to add with the appropriate properties set.

You can add a column in code something like this:

        Dim col As New DataGridViewTextBoxColumn
        col.DataPropertyName = "PropertyName"
        col.HeaderText = "SomeText"
        col.Name = "colWhateverName"

Be sure to set the appropriate property name etc. You can copy it from the existing column too...

col.DataPropertyName = NameDataGridViewTextBoxColumn.DataPropertyName

For example.