[英]Adding rows to a datatable while looping through a datagridview
我有一个从MySQL数据库填充的datagridview。 我正在遍历它来验证信息,并在验证信息时将记录添加到数据表中。
我遇到的问题是我当前的代码仅添加了第一条记录。 我希望它添加一条记录,继续前进,然后添加另一条记录,继续前进,等等。
有任何想法吗?
Private Sub ProcessorWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles ProcessorWorker.DoWork
Console.WriteLine("ProcessorWorker Invoked...")
Try
Dim dt As New DataTable
Dim entryid As String = " "
For Each row As DataGridViewRow In orderslist.Rows
If row.Cells("member_id").Value.ToString IsNot Nothing Then
entryid = row.Cells("entry_id").Value.ToString
If entryid <> "" Then
Dim memberid As String = row.Cells("member_id").Value.ToString
Dim cn1 As New MySqlConnection
cn1.ConnectionString = ###myconnectionstring###
Dim vm_components As New MySqlDataAdapter("Select * FROM website_orders WHERE order_id= '" & entryid & "'", cn1)
Dim vm_components_table As New DataTable
vm_components.Fill(vm_components_table)
Dim row1 As DataRow
row1 = vm_components_table.Select("order_id = '" & entryid & "'").FirstOrDefault()
If Not row1 Is Nothing Then
If row1.Item("cart_id") IsNot Nothing Then web_cartid = row1.Item("cart_id").ToString
If row1.Item("email") IsNot Nothing Then web_email = row1.Item("email").ToString
If row1.Item("member_id") IsNot Nothing Then web_memberid = row1.Item("member_id").ToString
If row1.Item("firstname") IsNot Nothing Then web_firstname = row1.Item("firstname").ToString
If row1.Item("lastname") IsNot Nothing Then web_lastname = row1.Item("lastname").ToString
If row1.Item("company") IsNot Nothing Then web_company = row1.Item("company").ToString
If row1.Item("address1") IsNot Nothing Then web_address1 = row1.Item("address1").ToString
If row1.Item("address2") IsNot Nothing Then web_address2 = row1.Item("address2").ToString
If row1.Item("city") IsNot Nothing Then web_city = row1.Item("city").ToString
If row1.Item("postcode") IsNot Nothing Then web_postcode = row1.Item("postcode").ToString
End If
dt.Columns.Add("Product Ordered", Type.GetType("System.String"))
dt.Columns.Add("Operating System", Type.GetType("System.String"))
dt.Columns.Add("Company", Type.GetType("System.String"))
dt.Columns.Add("Customer", Type.GetType("System.String"))
dt.Columns.Add("Email Address", Type.GetType("System.String"))
WebOrders.DataSource = dt
Dim dr As DataRow
dr = dt.NewRow
dr("Product Ordered") = web_servertype
dr("Operating System") = web_os
dr("Company") = "WORLD"
dr("Customer") = web_firstname & " " & web_lastname
dr("Email Address") = web_email
dt.Rows.Add(dr)
WebOrders.AllowUserToAddRows = False
End If
End If
Next
Catch ex As Exception
End Try
End Sub
问题是您将add语句放入for每个循环中。 因此,在第二次迭代中,您尝试将一个名为Product Ordered
现有列添加到DataTable
。 这就是引发异常并到达catch块的原因。 解决方案是将add语句放在for每个循环之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.