使用这些代码后,我可以添加一行并在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
。您填充它,然后将其提交到底层DataTable
,DataGridView
将显示它,例如
Dim newRow = DirectCast(myBindingSource.AddNew(), DataRowView)
newRow("SomeColumn") = someValue
myBindingSource.EndEdit()
总之,不要直接使用DataTable
的DefaultView
。请将DataTable
绑定到BindingSource
,并将其绑定到UI。务必使用BindingSource
来操作和导航代码中的绑定数据。