如何用程序添加行数据网格视图



使用这些代码后,我可以添加一行并在datagridview中写入数据吗?

我可以写手册,但我不能用按钮写

.Rows(0).Cells(0).Value = CARKOD.Text
.Rows(s).Cells(1).Value = UNVAN.Text
.Rows(s).Cells(2).Value = ACIKLAMA

With MAHSUP
Dim dt1 = New DataTable()
myDA1 = New OleDbDataAdapter(cm1)
Dim builder1 As OleDbCommandBuilder = New OleDbCommandBuilder(myDA1)
myDataSet1 = New DataSet()
myDA1.Fill(myDataSet1, "CARTH001")
.DataSource = myDataSet1.Tables("CARTH001").DefaultView
End With ```

数据绑定的全部意义在于控件显示数据源的内容。然后,它为用户提供了一个与该数据源交互的UI。如果您想更改代码中的数据,请使用数据源,而不是UI。

当将DataTable绑定到DataGridView时,正确的做法是在它们之间使用BindingSource,并使用它来访问代码中的数据。你可以在设计器中添加BindingSource,然后像这样绑定:

Dim myDataTable As New DataTable
myDataAdapter.Fill(myDataTable)
myBindingSource.DataSource = myDataTable
myDataGridView.DataSource = myBindingSource

要添加一行,请在BindingSource上调用AddNew。这将返回新的项目,即DataRowView。您填充它,然后将其提交到底层DataTableDataGridView将显示它,例如

Dim newRow = DirectCast(myBindingSource.AddNew(), DataRowView)
newRow("SomeColumn") = someValue
myBindingSource.EndEdit()

总之,不要直接使用DataTableDefaultView。请将DataTable绑定到BindingSource,并将其绑定到UI。务必使用BindingSource来操作和导航代码中的绑定数据。

最新更新