Link to home
Start Free TrialLog in
Avatar of heartland
heartland

asked on

write data to DataGridView

Hi,

I am new to DataGridView contol in VB.NET 2005.  Here is the question:  I used a datatable to populate DataGridView first:

Dim dt as datatable
'logic to fill datatable
DataGridView.DataSource = dt

This worked fine.

I then need to populate the same DataGridView with another set of data:

Dim sColumnHeader() As String = {"ColA", "ColB", "ColC", "ColD"}
For i = 0 To DataGridView.Columns.Count - 1
      DataGridView.Columns(i).Dispose()
Next

DataGridView.ColumnCount = sColumnHeader.GetUpperBound(0) + 1
For i = 0 To sColumnHeader.GetUpperBound(0)
     DataGridView.Columns(i).Name = sColumnHeader(i)
Next

For i = 0 To 10
      sColA = A & i
      sColB = B & i
      sColC = C & i
      sColD = D & i
      Dim rows() As Object = {sColA, sColB, sColC, sColD}
      DataGridView.Rows.Add(rows)
Next

I received error message of "ColumnCount property cannot be set on a data-bound DataGridView control".  How do I get a fresh start of a DataGridView after data bounding?

Thanks in advance for your help.

Heartland
Avatar of Solar_Flare
Solar_Flare

why can you not just databind the table to the datagridview?

datagridview.Datasource = dt

that will rebind the entire datagrid, and if you have autogenerate columns = true then it will also generate the datagridview's column based on dt's columns.
ASKER CERTIFIED SOLUTION
Avatar of Manish Chhetia
Manish Chhetia
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of heartland

ASKER

Hi Manch,

Yes, it works fine.  Stupid me.  Well, as a matter of fact, I found it by myself after sending my message.  But, your solution is good.  it was too easy for you. Would you mind give me another help.  Why I get a extra empty row in the last row of DataGridView after loading data into it.  For example, the DataGridView will have 11 rows with 11th row empty if I want to write 10 rows of data into it?  Is there any way not writing this extra row?   I know it is not the original question anymore.

Thanks in advance.

heartland