如何在DataGridView中删除数据?

问题描述 投票:0回答:1

我在我的项目中有一个DataGridView,如果数据中的一个单元格显示为“Void”,我希望查看特定数据但是当我使用代码时,我使用DataGridView中的所有数据都是触发意味着接受第一个参数尽管所述数据中的一些数据仍为“活动”,但所有数据均为“活动”。

以下是我的代码:

For Each r As DataGridViewRow In frmCheckOut_Room.DataGridView2.Rows
    If (r.Cells(9).Value) = "Void" Then
        r.DefaultCellStyle.ForeColor = Color.Red
        r.DefaultCellStyle.Font = New Font("Microsoft Sans Serif", 8, FontStyle.Strikeout)
    ElseIf (r.Cells(9).Value) = "Active" Then
        r.DefaultCellStyle.Font = New Font("Microsoft Sans Serif", 8)
        r.DefaultCellStyle.BackColor = Color.Orange
    End If
Next
vb.net datagridview
1个回答
0
投票

你好 我使用GridFormatting事件来实现这一目标。例如:

 Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
    If e.ColumnIndex = DataGridView2.Columns("YOUR_COLUMN_NAME").Index AndAlso e.Value IsNot Nothing Then
        If (e.Value = "Void") Then
            DataGridView2.Rows(e.RowIndex).DefaultCellStyle.Font = New Font("Microsoft Sans Serif", 8, FontStyle.Strikeout)
            DataGridView2.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red
        ElseIf (e.Value = "Active") Then
           DataGridView2.Rows(e.RowIndex).DefaultCellStyle.Font = New Font("Microsoft Sans Serif", 8)
           DataGridView2.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Orange
        End If
    End If
End Sub

我更喜欢使用列名而不是列索引,但如果您希望可以替换If e.ColumnIndex = DataGridView2.Columns("YOUR_COLUMN_NAME").Index Then 附:

If e.ColumnIndex = 9 Then

我没有机会测试它,所以如果您有任何问题或疑问,请不要犹豫,给我留言。 问候 编辑:如果要标记网格中包含单词“Active”或“Void”的每个单元格,只需使用以下代码:

Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
If (e.Value.GetType() = GetType(String)) Then
    If (e.Value = "Void") Then
        DataGridView2(e.ColumnIndex, e.RowIndex).Style.Font = New Font("Microsoft Sans Serif", 8, FontStyle.Strikeout)
        DataGridView2(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
    ElseIf (e.Value = "Active") Then
       DataGridView2(e.ColumnIndex, e.RowIndex).Style.Font = New Font("Microsoft Sans Serif", 8)
       DataGridView2(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Orange
    End If
End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.