循环遍历datagridview

时间:2011-10-15 10:22:24

标签: vb.net datagridview

我是一个Windows应用程序。包含名为BOM和BOMSelected的表格..

BOM中有datagridview,其中包含复选框列。当用户选中复选框时,应在其他表格的Selectedgridview中看到所选行,SelectedBom ..

我已编码,但没有让它工作..有些错误..

你能帮忙吗?

非常感谢您的帮助..

这就是我所做的!!

Public Class SelectedBom

    Private Sub SelectedBom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'HemDatabase1DataSet4.partno' table. You can move, or remove it, as needed.
        'Me.PartnoTableAdapter.Fill(Me.HemDatabase1DataSet4.partno)

        Dim count As Integer = 0

        For j As Integer = 0 To BOM.dgv1.RowCount - 1

            If BOM.dgv1.Rows(j).Cells(0).Value = True Then

                Dim ro As New DataGridViewRow
                DataGridView2.Rows.Add(ro)

                For i As Integer = 0 To BOM.dgv1.ColumnCount - 1
                    Me.DataGridView2.Rows(count).Cells(i).Value = BOM.dgv1.Rows(j).Cells(i).Value
                Next

                count += 1

            End If

        Next

    End Sub
End Class

2 个答案:

答案 0 :(得分:1)

尝试,

For Each row As DataGridViewRow In BOM.dgv1.Rows
  Dim obj(row.Cells.Count - 1) As Object
  For i = 0 To row.Cells.Count - 1
      obj(i) = row.Cells(i).Value
  Next
  Me.DataGridView2.Rows.Add(obj)
Next

编辑:

演示:

以BOM表格添加Button1和DataGridView1

Public Class BOM
    Public Class Sample
        Public Property Satus As Boolean
        Public Property Name As String
        Public Property ID As Integer
    End Class
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        SelectedBom.Show()
    End Sub
    Private Sub BOM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim myList As New List(Of Sample)
        myList.Add(New Sample() With {.ID = 1, .Name = "A"})
        myList.Add(New Sample() With {.ID = 2, .Name = "B"})
        myList.Add(New Sample() With {.ID = 3, .Name = "C"})
        DataGridView1.DataSource = myList
    End Sub
End Class

以SelectBOM格式添加DataGridView1

Public Class SelectedBom

    Private Sub SelectedBom_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim i As Integer = 0
        DataGridView1.AutoGenerateColumns = False
        DataGridView1.Columns.Add("Name", "Name")
        DataGridView1.Columns.Add("No", "No")
        For Each row As DataGridViewRow In BOM.DataGridView1.Rows

            If DirectCast(row.Cells(0).Value, Boolean) Then
                DataGridView1.Rows.Add(row.Cells(1).Value, row.Cells(2).Value)
            End If
        Next
    End Sub
End Class

答案 1 :(得分:0)

也许您应该使用:

而不是使用for each语句
for istep as integer = 0 to datagridview.rowcount - 2

使用for each语法,当您沿着行走时,无法为单个行指定值。