Insert new row inside DataGridView

陌路散爱 提交于 2020-01-06 08:45:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!