vb.net 在 DataGridView 中插入新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16776539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert new row inside DataGridView
提问by BAD_SEED
In my VB class I have defined this attribute as class variable:
在我的 VB 类中,我将此属性定义为类变量:
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]:
这段代码完成了它的工作:从数据库中读取数据并插入到网格中。现在我将在该网格中手动添加新行,因此我编写了此代码来代替[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?
但没有任何反应DataGridView(即没有插入行)。怎么了?
回答by matzone
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

