Reputation: 116
For Each row As DataRow In dgrFarms.Rows
Dim sendtroopid As Integer
sendtroopid = row("idColumn")
'Do Something
Next
I've been trying to get a loop through a row in just one column in VB.NET for a while now, and i've done my homework on it too. When i use that code above I get:
Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Data.DataRow'.
I saw another guide which told me to do:
For Each row As DataGridView In dgrFarms.Rows
sendtroopid = row("idColumn")
'Do Something
Next
But that gives me the error:
Overload resolution failed because no accessible 'Item' accepts this number of arguments.
(That's a blue underline on 'Row("idColumn") )
Upvotes: 0
Views: 18565
Reputation: 11
This is a function I use in all my Apps:
''' <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
Upvotes: 1
Reputation: 17845
The code should be:
For Each row As DataGridViewRow In dgrFarms.Rows
sendtroopid = row.Cells("idColumn").Value
'Do Something
Next
Note that each row is a DataGridViewRow
, not a DataGridView
. Also, you get the contents of a specific cell from this row with the Cells
property.
Upvotes: 3
Reputation: 13744
Did you try to run your code by checking the itemType of the row being bound? try placing your code between:
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
'do loop
end if
Upvotes: 0