操纵datagridview vb net中的数据

时间:2013-05-25 08:47:32

标签: vb.net winforms

我有一张桌子销售(发票,dateinv,卖家,等级)

Dim sql As String = "SELECT * FROM Sales"
Dim daHeader As New SqlDataAdapter(sql, Conn)
Dim dtSales As New DataTable
daHeader.Fill(dtSales)

dgvheader.AutoGenerateColumns = False
dgvHeader.Columns.Add(New DataGridViewTextBoxColumn() With {.HeaderText = "Date", .DataPropertyName = "dateinv"}) 
dgvHeader.Columns.Add(New DataGridViewTextBoxColumn() With {.HeaderText = "Seller", .DataPropertyName = "seller"}) 
dgvHeader.Columns.Add(New DataGridViewTextBoxColumn() With {.HeaderText = "Grade", .DataPropertyName = "grade"}) 
dgvHeader.DataSource = dtSales

等级栏的值在1-3之间 如何在Datagridview中显示Grade值为:
1 =“优秀”
2 =“好”
3 =“足够”

感谢,,

2 个答案:

答案 0 :(得分:1)

您可以挂钩DataGridView.CellFormatting活动

修改

如果您设置了列的名称,则@matzone中的代码将有效,但您只设置了HeadertextDataPropertyName

所以试试这个:

Private Sub dgvHeader_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvHeader.CellFormatting

Dim sHeader As String = dgvHeader.Columns(e.ColumnIndex).HeaderText

    If sHeader = "Grade" Then

        If e IsNot Nothing Then
            If e.Value IsNot Nothing Then
                Select Case e.value '-----------> assumed grade as numeric field
                  Case 1 : e.Value = "Excellent"
                  Case 2 : e.Value = "Good"
                  Case 3 : e.Value = "Enough"
                End Select                    
            End If        
        End If
        e.FormattingApplied = True
    End If
End Sub

我只改变了这一行:

 Dim sHeader As String = dgvHeader.Columns(e.ColumnIndex).HeaderText

答案 1 :(得分:1)

使用datagridview.cellformatting事件

Private Sub dgvHeader_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvHeader.CellFormatting

Dim sHeader As String = dgvHeader.Columns(e.ColumnIndex).Name

    If ucase(sHeader) = "GRADE" Then

        If e IsNot Nothing Then
            If e.Value IsNot Nothing Then
                Select Case e.value '-----------> assumed grade as numeric field
                  Case 1 : e.Value = "Excellent"
                  Case 2 : e.Value = "Good"
                  Case 3 : e.Value = "Enough"
                End Select                    
            End If        
        End If
        e.FormattingApplied = True
    End If
End Sub