简体   繁体   中英

VB.NET DataGridView rows

NET Hi I'm new in VB NET and I'm trying to check if all values in the same row of a datagridview are the same. Exemple :

For Each row In DataGridView1.Rows
       If 'all values in row are not the same' Then
           row.DefaultCellStyle.BackColor = Color.Red
       End if
Next

Tell me if there is anything that you don't understand in my question ^^

Thank you in advance for your help! :P

May be better if you use handler of .RowPrepaint

private sub datagridivew_RowPrepaint(sender as Object, e as DataGridViewRowPrePaintEventArgs) Handles datagridview.RowPrePaint
    if e.RowIndex >= 0 then
        Dim dgvr as DataGridViewRow = DirectCast(sender, DataGridView).Rows(e.RowIndex)
        if IsAllValuesAreSame(dgvr) = True Then
            dgvr.DefaultCellStyle.BackColor = Color.Red    
        End If
    End If
End Sub

Then you don't need to loop all rows one more time after all rows initialized.
And function for checking all values of row:

private function IsAllValuesAreSame(dgvr as DataGridViewRow) as Boolean
    Dim distinctQnt As Int32 = (From cell As DataGridViewCell In dgvr.Cells
                                Where cell.ColumnIndex >= 0
                                Select cell.Value).Distinct().Count()
    Return (distinctQnt = 1)
End Function

You need to match the value of all the cells in each row with one cell in that row to know if all cells in that row have the same value. Below, I'm giving you the simplest method to do it and I am choosing the value of the first column of each row to verify if the values of other columns in that row are equal to it. If all the columns/cells of a row don't have the same value, then that row's back color will turn red.

    For x = 0 To DataGridView1.RowCount - 1
        For y = 0 To DataGridView1.ColumnCount - 1
            If DataGridView1.Item(y, x).Value = DataGridView1.Item(0, x).Value Then
                'yes
            Else
                'no
                 DataGridView1.Rows.Item(x).DefaultCellStyle.BackColor = Color.Red
            End If
        Next
    Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM