VB.NET - 循环遍历数据网格中的行的问题

时间:2012-03-27 15:53:32

标签: vb.net datagrid datagridview

 For Each row As DataRow In dgrFarms.Rows
        Dim sendtroopid As Integer
        sendtroopid = row("idColumn")
        'Do Something
Next

我一直试图在VB.NET中的一列中循环一段时间,我已经完成了我的功课了。当我使用上面的代码时,我得到:

无法将'System.Windows.Forms.DataGridViewRow'类型的对象强制转换为'System.Data.DataRow'。

我看到另一个告诉我的指南:

For Each row As DataGridView In dgrFarms.Rows
        sendtroopid = row("idColumn")
        'Do Something
Next

但这给了我错误:

重载解析失败,因为没有可访问的“Item”接受此数量的参数。

(这是'Row(“idColumn”)上的蓝色下划线)

3 个答案:

答案 0 :(得分:3)

代码应为:

For Each row As DataGridViewRow In dgrFarms.Rows
    sendtroopid = row.Cells("idColumn").Value
    'Do Something
Next

请注意,每行都是DataGridViewRow,而不是DataGridView。此外,您还可以使用Cells属性从此行获取特定单元格的内容。

答案 1 :(得分:1)

这是我在所有应用中使用的功能:

''' <summary>
''' Provides the Properties and Methods to insert each Column from eaqch Row in a Dataset
''' when given a Dataset and a List Box 
''' </summary>
''' <remarks></remarks>
Public Class clsDisplayDataset
    Private mstrClsTitle As String = "clsDisplayDataset"

    ''' <summary>
    ''' For Each Row and Each Column create a single line to be inserted into the 
    ''' List Box
    ''' </summary>
    ''' <param name="idsDataset"></param>
    ''' <param name="ilstListBox"></param>
    ''' <returns>True   -    When successful
    '''          False  -    When unsuccessful</returns>
    ''' <remarks></remarks>
    Public Function DisplayDataSet(ByVal idsDataset As DataSet,
                                   ByRef ilstListBox As ListBox) As Boolean
        Dim lstrRowValue As String = ""
        Try
            For Each ldsRow As DataRow In idsDataset.Tables(0).Rows
                lstrRowValue = ""
                For Each ldsCol As DataColumn In idsDataset.Tables(0).Columns
                    lstrRowValue = lstrRowValue & ldsRow(ldsCol.ColumnName).ToString() & vbTab
                Next
                ilstListBox.Items.Add(lstrRowValue)
            Next
            Return True
        Catch ex As Exception
            DisplayDataSet = False
            Throw New Exception(mstrClsTitle & ".DisplayDataSet" & vbCrLf &
                                "Error Number      [" & Err.Number & vbCrLf &
                                "Error Description [" & Err.Description & "]" & vbCrLf &
                                "Failed to insert columns into List Box")
        End Try
    End Function
End Class

答案 2 :(得分:0)

您是否尝试通过检查绑定行的itemType来运行代码?尝试将代码置于:

之间
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
'do loop
end if