将行添加到DataGridView

时间:2017-04-26 11:14:36

标签: sql vb.net datagridview datagrid rows

是的,我知道还有其他帖子,但我无法理解要更改的内容或在何处使解决方案适合我的代码。

错误:

  

当控件受数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。

代码:

Public Sub dsLoadEvents()
    dsConnectionE = New OleDbConnection
    dsConnectionE.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=DataSourceDB.accdb"
    dsDataAdapterE = New OleDbDataAdapter
    dsDataAdapterE.SelectCommand = New OleDbCommand
    dsDataAdapterE.SelectCommand.Connection = dsConnectionE
    dsDataAdapterE.SelectCommand.CommandText = "SELECT * FROM Event"
    dsDataAdapterE.SelectCommand.CommandType = CommandType.Text
    dsConnectionE.Open()
    dsDataSetE = New DataSet
    dsDataAdapterE.Fill(dsDataSetE, "dataSetEvents")
    dsConnectionE.Close()
    Form3.dgdEvents.AutoGenerateColumns = True
    Form3.dgdEvents.DataSource = dsDataSetE
    Form3.dgdEvents.DataMember = "dataSetEvents"
End Sub

这是首次打开程序时加载事件的位置。我正在努力向数据库添加内容但是我尝试使用以下代码将其添加到DataGridView,但它给了我上面的错误。

Form3.dgdMembers.Rows.Add(New String() {Form3.tbceid.Text, Form3.tbfn.Text, Form3.dtpesd.Value, Form3.dtpdob.Value, Form3.tbal2.Text, Form3.tbal1.Text, Form3.tbpgfn.Text, Form3.tbpgsn.Text, Form3.tbcpp.Text, Form3.tbelid.Text})

1 个答案:

答案 0 :(得分:0)

这是一个示例,我在一个类中加载数据,传回一个DataSet(我们可以只使用一个DataTable),在表单加载中将DataTable加载到DataGridView中。

在按钮单击事件中,我们将DataGridView DataSource转换为DataTable并使用硬编码数据添加新行,但当然这可以来自TextBox控件。

班级

Public Class Sample1
    Private Builder As New OleDbConnectionStringBuilder With
    {
        .Provider = "Microsoft.ACE.OLEDB.12.0",
        .DataSource = IO.Path.Combine(Application.StartupPath, "Database1.accdb")
    }
    Public Property dsDataSetE As DataSet
    Public Function LoadCustomers() As DataSet

        dsDataSetE = New DataSet

        Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
            Dim commandText As String = "SELECT Identifier, ContactTitle, Country, CompanyName FROM Customers"
            Dim dsDataAdapterE = New OleDbDataAdapter(commandText, Builder.ConnectionString)
            cn.Open()
            dsDataAdapterE.Fill(dsDataSetE, "Customers")
            dsDataSetE.Tables("Customers").Columns("Identifier").ColumnMapping = MappingType.Hidden
        End Using

        Return dsDataSetE

    End Function
End Class

表格代码

Public Class StackOverFlowForm1
    Private Operations As New Sample1
    Private Sub StackOverFlowForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim ds As DataSet = Operations.LoadCustomers
        DataGridView1.DataSource = ds.Tables("Customers")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        CType(DataGridView1.DataSource, DataTable) _
            .Rows.Add(New Object() {Nothing, "Owner", "USA", "My company"})
    End Sub
End Class

以上是将数据添加到数据绑定DataGridView的一种方法。我们可以将类中的代码放在表单中,但最好将后端操作与前端代码分开。

希望这有帮助。