问题
In my VB class I have defined this attribute as class variable:
Friend WithEvents dgw As System.Windows.Forms.DataGridView
Somewhere in the same class is defined a property:
Private Sub mySub(...)
Dim aDataAdapter As SqlDataAdapter
Dim aDataSet = New DataSet
aDataAdapter = New SqlDataAdapter("exec something")
aDataAdapter.Fill(aDataSet)
Me.dgw.DataSource = aDataSet.Tables(0)
' [PLACEHOLDER]
End Sub
This code do its job: data are readed from the database and are inserted inside the grid. Now I would manually add new row inside that grid so I wrote this code in place of [PLACEHOLDER]
:
Dim emptyRow As DataGridViewRow
emptyRow.SetValues(New String() {"a", "b", "c", "d", "e"})
Me.dgw.Rows.Insert(2, emptyRow)
but nothing happen to the DataGridView
(i.e. No rows are inserted). What's wrong?
回答1:
Your datagrid bound to a data source, so then you should be adding rows in that data source
Dim drCopy as DataRow
Dim tbl as DataTable = aDataSet.Tables(0)
drCopy=tbl.NewRow()
drCopy.item(0)="a"
drCopy.item(1)="b"
drCopy.item(2)="c"
drCopy.item(3)="d"
drCopy.item(4)="e"
tbl.Rows.Add(drCopy)
Me.dgw.datasource = tbl
来源:https://stackoverflow.com/questions/16776539/insert-new-row-inside-datagridview