For循环不迭代datagridview数据 [英] For loop not iterating datagridview data

查看:79
本文介绍了For循环不迭代datagridview数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试遍历datagridview中的元素时,出现错误该行已在表中".该错误发生在代码的添加新行"部分.我一直在为此苦苦挣扎,似乎找不到解决办法.有人可以帮忙吗?我敢肯定,这只是我没看到的简单事情.下面是代码.提前谢谢.



选择*从Testdat
da2 =新的MySqlDataAdapter(sql2,conn2)
da2.Fill(ds2)
昏暗的cb作为新的MySqlCommandBuilder(da2)
将dsNewRow变暗为DataRow
dsNewRow = ds2.Tables(0).NewRow
''按字符串的昏暗视图
Dim i As Integer = 0
对于每行,作为DataGridView1.Rows中的DataGridViewRow
dsNewRow.Item = DataGridView1.Rows(i).Cells(0).Value
''查看= DataGridView1.Rows(i).Cells(0).Value
dsNewRow.Item(= DataGridView1.Rows(i).Cells(1).Value
dsNewRow.Item = DataGridView1.Rows(i).Cells(2).Value
我+ = 1
ds2.Tables(0).Rows.Add(dsNewRow)(此处发生错误)
下一行
da2.Update(ds2.Tables(0))

When I try to loop through the elements in a datagridview I''m getting an error "This row already belongs in the table". The error occurs at the add new row section of code. I have been struggling with this and cannot seem to find a solution. Could someone help? I''m sure it''s just something simple that I am not seeing. Below is the code. Thanks in advance.



SELECT * FROM Testdat
da2 = New MySqlDataAdapter(sql2, conn2)
da2.Fill(ds2)
Dim cb As New MySqlCommandBuilder(da2)
Dim dsNewRow As DataRow
dsNewRow = ds2.Tables(0).NewRow
''Dim View As String
Dim i As Integer = 0
For Each row As DataGridViewRow In DataGridView1.Rows
dsNewRow.Item = DataGridView1.Rows(i).Cells(0).Value
''View = DataGridView1.Rows(i).Cells(0).Value
dsNewRow.Item( = DataGridView1.Rows(i).Cells(1).Value
dsNewRow.Item = DataGridView1.Rows(i).Cells(2).Value
i += 1
ds2.Tables(0).Rows.Add(dsNewRow) (error occurs here)
Next row
da2.Update(ds2.Tables(0))

推荐答案

我很懒,我没有时间创建一个项目来测试您的代码.通过阅读代码,我可以知道您没有正确使用dsNewRow的Item属性.

这里可能存在违反主键的情况.您试图将所有字段复制到新行,导致新行与现有行相同,从而导致显示错误.
I am lazy and I don''t have time to create a project to test your code. By reading your code I can tell that you are not using the Item property of dsNewRow correctly.

There may be a primary key violation in here. You are trying to copy all the fields to the new row, resulting a new row to be identical to an existing row, which causes the error to be shown.


将行
dsNewRow = ds2.Tables(0).NewRow

在for循环内.这将是可行的.就这样

inside the for loop. It will be works. that''s all


这篇关于For循环不迭代datagridview数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆