locked
Looping through cells in DataGridView column RRS feed

  • Question

  • How do you loop through a name column in a DataGridView?  What is the collection?  The following below does not work.

    For each X in DataGridView.Columns("Name")

    Next

    Thanks

    EM
    Friday, August 15, 2008 3:13 AM

Answers

  • ExcelMonkey said:

    How do you loop through a name column in a DataGridView?  What is the collection?  The following below does not work.

    For each X in DataGridView.Columns("Name")


    Hi EM,

    Calle's idea is good.

    Besides, you can loop through cells in DataGridView via RowIndex and ColumnIndex.

            Dim rowIndex As Int32 = 0  
            Dim colIndex As Int32 = 0  
     
            'Loop through each cell in DataGridView column "Name" (Assuming it's the second column)  
            For rowIndex = 0 To DataGridView1.RowCount - 2 'Her "-2"(not "-1") is to skip the NewRow at the end.
                MessageBox.Show(DataGridView1.Rows(rowIndex).Cells("Name").Value.ToString)  
                ' or  
                MessageBox.Show(DataGridView1.Rows(rowIndex).Cells(1).Value.ToString) 'Note: Column Index is based on zero.  
            Next 
     
            'Loop through all cell in entire DataGridView  
            For rowIndex = 0 To DataGridView1.RowCount - 2  
                For colIndex = 0 To DataGridView1.ColumnCount - 1  
                    MessageBox.Show(DataGridView1.Rows(rowIndex).Cells(colIndex).Value.ToString)  
                Next 
            Next 

    Additionally, you can reference to specific cell in DataGridView control like this:

       DataGridView1.CurrentCell.Value

       DataGridView1(ColumnIndex, RowIndex).Value

       DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value

      DataGridView1.Rows(RowIndex).Cells("ColumnName").Value



    Best regards,
    Martin Xie

    Thursday, August 21, 2008 4:44 AM
  • There's no ready made collection to be used. You will need to get the cell from each row, something like this;

     
            For Each row As DataGridViewRow In Me.DataGridView1.Rows  
                If (Not row.IsNewRow) Then 
                    Dim cell As DataGridViewCell = row.Cells("Column1")  
     
                    ' Do something with cell...  
                End If 
            Next 
     
     

    Checking if the row is a new row is optional.

    /Calle
    - Still confused, but on a higher level -
    Friday, August 15, 2008 8:15 AM

All replies

  • There's no ready made collection to be used. You will need to get the cell from each row, something like this;

     
            For Each row As DataGridViewRow In Me.DataGridView1.Rows  
                If (Not row.IsNewRow) Then 
                    Dim cell As DataGridViewCell = row.Cells("Column1")  
     
                    ' Do something with cell...  
                End If 
            Next 
     
     

    Checking if the row is a new row is optional.

    /Calle
    - Still confused, but on a higher level -
    Friday, August 15, 2008 8:15 AM
  • ExcelMonkey said:

    How do you loop through a name column in a DataGridView?  What is the collection?  The following below does not work.

    For each X in DataGridView.Columns("Name")


    Hi EM,

    Calle's idea is good.

    Besides, you can loop through cells in DataGridView via RowIndex and ColumnIndex.

            Dim rowIndex As Int32 = 0  
            Dim colIndex As Int32 = 0  
     
            'Loop through each cell in DataGridView column "Name" (Assuming it's the second column)  
            For rowIndex = 0 To DataGridView1.RowCount - 2 'Her "-2"(not "-1") is to skip the NewRow at the end.
                MessageBox.Show(DataGridView1.Rows(rowIndex).Cells("Name").Value.ToString)  
                ' or  
                MessageBox.Show(DataGridView1.Rows(rowIndex).Cells(1).Value.ToString) 'Note: Column Index is based on zero.  
            Next 
     
            'Loop through all cell in entire DataGridView  
            For rowIndex = 0 To DataGridView1.RowCount - 2  
                For colIndex = 0 To DataGridView1.ColumnCount - 1  
                    MessageBox.Show(DataGridView1.Rows(rowIndex).Cells(colIndex).Value.ToString)  
                Next 
            Next 

    Additionally, you can reference to specific cell in DataGridView control like this:

       DataGridView1.CurrentCell.Value

       DataGridView1(ColumnIndex, RowIndex).Value

       DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value

      DataGridView1.Rows(RowIndex).Cells("ColumnName").Value



    Best regards,
    Martin Xie

    Thursday, August 21, 2008 4:44 AM
  • Hi

    Expanding feature more.  how would i compare a value in the datagridview to a textbox value.

    for example,

    in the datagridview therea are 3 columns (partid,partdes,qty) and in my textbox i have a text part called "SAUSAGE"

    what i want to do is for the datagridview to go through column (0) - part id and look for the value called SAUSAGE.  IF existed, do something and if not msgbox (...).


    is tis possible to do?

    thanks,
    Tom_tak
    Friday, February 6, 2009 8:33 PM
  • takraw_ said:

    Expanding feature more.  how would i compare a value in the datagridview to a textbox value.
    for example,
    in the datagridview therea are 3 columns (partid,partdes,qty) and in my textbox i have a text part called "SAUSAGE"
    what i want to do is
    for the datagridview to go through column (0) - part id and look for the value called SAUSAGE.  IF existed, do something and if not msgbox (...).

    Hi Tom_tak,

    Here is code sample you desired. Please take it a try.

        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click  
            Dim rowIndex As Int32 = 0  
            Dim idCellVal As String = "" 
            Dim isExist As Boolean = False 
     
            'Loop through each cell in DataGridView 1st column "partid"  
            For rowIndex = 0 To DataGridView1.RowCount - 2 'Her "-2"(not "-1") is to skip the NewRow at the end.   
                idCellVal = DataGridView1.Rows(rowIndex).Cells("partid").Value.ToString  
                If idCellVal = TextBox1.Text Then 
                    isExist = True 'Once found,change to True   
                    ' Do something  
                End If 
            Next 
     
            If isExist = False Then 'If still not found after Loop through entire 1st column  
                MessageBox.Show("Not Found!")  
            End If 
     
        End Sub 



    Best regards,
    Martin Xie

    Monday, February 9, 2009 3:41 AM
  • Thank you so much for the reply.  this helps me a lot. 

    i have one more questions:

    let say i found the partid and it existed.  how to i deduct the qty from that cell.

    i.e) |PART ID | PART DESC | QTY|
          ------------------------------------
           FISH          FISH - G        10


    how to i from the datagriview once we find the partid, how to i deduct the QTY column to make it 9. ...and so on (decrement) evertime i click on the bttn.

    thanks so much for the help...

    tom
    Tuesday, February 10, 2009 8:49 PM
  • takraw_ said:

    let say i found the partid and it existed.  how to i deduct the qty from that cell.

    i.e) |PART ID | PART DESC | QTY|
          ------------------------------------
           FISH          FISH - G        10


    how to i from the datagriview once we find the partid, how to i deduct the QTY column to make it 9. ...and so on (decrement) evertime i click on the bttn.


    Public Class Form1  
     
        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click  
            Dim rowIndex As Int32 = 0  
            Dim idCellVal As String = "" 
            Dim isExist As Boolean = False 
     
            'Loop through each cell in DataGridView 1st column "partid"     
            For rowIndex = 0 To DataGridView1.RowCount - 2 'Her "-2"(not "-1") is to skip the NewRow at the end.      
                idCellVal = DataGridView1.Rows(rowIndex).Cells("partid").Value.ToString  
                If idCellVal = TextBox1.Text Then 
                    DataGridView1.Rows(rowIndex).Cells("QTY").Value = Val(DataGridView1.Rows(rowIndex).Cells("QTY").Value) - 1 ' Decrement  
                    isExist = True 'Once found,change to True      
                    ' Do something     
                End If 
            Next 
     
            If isExist = False Then 'If still not found after Loop through entire 1st column     
                MessageBox.Show("Not Found!")  
            End If 
     
        End Sub 
     
    End Class 
    Thursday, February 12, 2009 5:39 AM
  • thanks Again.

    i ran into one problem:  when decrement the qty to 0.  once it hit 0 how do i remove that row?

    I.e): |part id | Part Des | Qty|
              ----------------------------
            FISH        FISH - G    10
            SHRIMP   SHRIMP-G  1

    when shrimp decrement after one loop it will become "0", when it become "0" how do i remove the row SHRIMP from the dgv?

    thanks
    tom
    Thursday, February 12, 2009 2:00 PM
  • takraw_ said:

    i ran into one problem: 
    when decrement the qty to 0.  once it hit 0 how do i remove that row?

    I.e): |part id | Part Des | Qty|
              ----------------------------
            FISH        FISH - G    10
            SHRIMP   SHRIMP-G  1

    when shrimp decrement after one loop it will become "0", when it become "0" how do i remove the row SHRIMP from the dgv?


    Here is code sample:
     
    Public Class Form1  
     
        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click  
            Dim rowIndex As Int32 = 0  
            Dim idCellVal As String = "" 
            Dim isExist As Boolean = False 
     
            'Loop through each cell in DataGridView 1st column "partid"        
            For rowIndex = 0 To DataGridView1.RowCount - 2 'Her "-2"(not "-1") is to skip the NewRow at the end.         
                idCellVal = DataGridView1.Rows(rowIndex).Cells("partid").Value.ToString  
                If idCellVal = TextBox1.Text Then 
                    isExist = True 'Once found,change to True             
     
                    If Val(DataGridView1.Rows(rowIndex).Cells("QTY").Value) <= 0 Then 
                        DataGridView1.Rows.RemoveAt(rowIndex)  
                    Else 
                        DataGridView1.Rows(rowIndex).Cells("QTY").Value = Val(DataGridView1.Rows(rowIndex).Cells("QTY").Value) - 1 ' Decrement     
                    End If 
     
                End If 
            Next 
     
            If isExist = False Then 'If still not found after Loop through entire 1st column        
                MessageBox.Show("Not Found!")  
            End If 
     
        End Sub 
     
    End Class 
    Friday, February 13, 2009 6:03 AM
  •  thank You Martin,

    when insert that code and running it i get this errors - i.  but i don't know how to go by fixing this. 

    here what is the error i am getting:(*Red is the error i'm getting)

    idCellVal = dgsalesorder.Rows(rowindex).cells("ID").value.tostring     -> Null ReferenceException was unhandled.  
                                                                                                                      Object reference not set to an instance of an object.


    here is my code:
    for rowindex = 0 to dgsalesorder.rowcount - 2
    idCellVal = dgSalesOrder.Row(rowindex).Cells("ID").value.tostring
    if idcellval=partid.text then
    isExist = true
    If Val(dgsalesorder.Rows(rowIndex).Cells("QTY").Value) <= 0 Then 
              
             dgsalesorder.Rows.RemoveAt(rowIndex)  
                   Else 
                dgsalesorder.Rows(rowIndex).Cells("QTY").Value = Val(dgsalesorder.Rows(rowIndex).Cells("QTY").Value) -1 ' Decrement     
                    End If 
     
                End If 
            Next 
     
            If isExist = False Then 'If still not found after Loop through entire 1st column        
                MessageBox.Show("Not Found!")  
            End If 
     

    thanks,
    tom
    Friday, February 13, 2009 1:35 PM
  • takraw_ said:

    idCellVal = dgsalesorder.Rows(rowindex).cells("ID").value.tostring     -> Null ReferenceException was unhandled.  
                                                                                                                      Object reference not set to an instance of an object.


    Hi Tom,

    Do you debug your code and figure out this issue?

    Please make sure that your DataGridView
    dgsalesorder contains a column named ID.

    You can consider sending your project (zip package) to me for investigation the issue.
    v-maxie@microsoft.com
    Monday, February 16, 2009 10:59 AM
  • Hi Martin,

    thanks for all your help.  I finally found my problem.

    now i ran into another problem. 

    when values are popluate in the datagridview.   if there are some empty or blank values in one of the the columns.  let say the Part ID column. 

    how to we remove the blank part id from teh datagridview when it gets loaded?

    thanks for you help

    Tom
    Wednesday, March 25, 2009 7:29 PM
  • Hi Martin,

     

    Thank you for this code from 2008. It really helps me.

    Then I tried adding a loop inside this loop but continue to get the error "Null reference exception was unhandled" before the loop ends. 

     For rowIndex = 0 To dgvVisit.RowCount - 2 
          MessageBox.Show(dgvVisit.Rows(rowIndex).Cells("CoPayCharge").Value.ToString)
    
          For rowIndex1 = 0 To dgvPayment.RowCount - 2 
            MessageBox.Show(dgvPayment.Rows(rowIndex).Cells("CoPayPaid").Value.ToString)
          Next
         
        Next
    

    My code is included.

     

    Can you help please?

    Kind regards, 


    Mike
    Sunday, July 31, 2011 12:48 PM
  • Hey,

    If I am not wrong it is

    For rowIndex = 0 To DataGridView1.RowCount - 1  
                For colIndex = 0 To DataGridView1.ColumnCount - 1  
                    MessageBox.Show(DataGridView1.Rows(rowIndex).Cells(colIndex).Value.ToString)  
                Next 
            Next 

    Friday, July 15, 2016 1:03 PM