2

What i want to do is get a value from the data grid. Example: a button onclick will change the color of the cell if the cell value is "test". i have the coding on how to change color but how to do the loop to search the value. Considering that only 1 column has a cell with the value test.

2 Answers 2

4

Try this ..

For y As Integer = 0 To DataGridView1.Rows.Count - 1

    For x  As Integer = 0 to DataGridView1.Columns.Count - 1

         If Datagridview.Rows(y).Cells(x).Value = "test" Then 

             DataGridView1..Rows(y).Cells(x).Style.ForeColor = Color.Red

         End If

    Next

Next 
0
1

You need to loop thru the rows and search for the text.

in this one you find out how to loop

Visual Basic, How do I read each row in a datagrid?

additionally if you have multiple columns and want to loop thru them too then you have to nest this peace in another loop, something like

    For i As Integer = 0 To DataGridView1.ColumnCount

        For Each row As DataGridViewRow In DataGridView1.Rows

            If Not row.IsNewRow Then
                If row.Cells(i).Value.ToString = "test" Then DataGridView1.Item(i, row.Index).Style.ForeColor = Color.Red
            End If
        Next

    Next i

Good luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.