在DataGridView中插入新行 [英] Insert new row inside DataGridView
本文介绍了在DataGridView中插入新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Friend WithEvents dgw As System.Windows.Forms。 DataGridView
同一个类的某个地方定义了一个属性:
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]
结束Sub
此代码执行其工作:数据从数据库中读取并插入到网格中。现在我将手动添加新的行内的网格,所以我写这个代码代替 [PLACEHOLDER]
:
Dim emptyRow As DataGridViewRow
emptyRow.SetValues(new String(){a,b,c,d,e})
Me.dgw.Rows.Insert(2,emptyRow)
但没有发生 DataGridView
(即不插入行)。什么问题?
解决方案
您的datagrid绑定到数据源,因此您应该在该数据源中添加行
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)
我.dgw.datasource = tbl
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?
解决方案
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
这篇关于在DataGridView中插入新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文