HeaderText与DataGrid中列的设计名称

时间:2013-06-14 19:47:24

标签: vb.net .net-4.0

我有以下代码可以正常工作,但它获取我的列的设计名称(DataGridViewTextBoxColumn11)而不是标题文本。如何更改我的代码以获取列上的标题文本而不是设计名称?

For Each row As DataGridViewRow In grdTransaction.Rows
            If grdTransaction.Item("DataGridViewTextBoxColumn11", row.Index).Value IsNot Nothing Then
                If grdTransaction("DataGridViewTextBoxColumn11", row.Index).Value.Equals(DBNull.Value) Then
                    row.DefaultCellStyle.BackColor = Color.Red
                End If
            End If
        Next

3 个答案:

答案 0 :(得分:0)

我对此类事情的约定是将项目命名为以dgc(DataGridColumn)为前缀的数据库列名称。因此标题为“客户名称”,列名为“dgcCustomerName”。如果表单或用户控件上有多个数据网格,并且在两个网格中的列中都有(例如)CustomerId,则将它们命名为同一会产生冲突。 dgcCustomerId是容器命名空间中的对象,允许您从中获取属性设置,而无需先指定网格成员资格。既然如此,在第二个网格中,您可能需要调用列'dgcInvoiceCustomerId'或'dgcLineItemCustomerId'。

答案 1 :(得分:0)

创建一个函数,从提供的列标题文本中返回DGV的列索引:

Private Function getColID(ByVal colHeaderText As String) As Integer
    Dim result As Integer = -1
    For Each col As DataGridViewColumn In grdTransaction.Columns
        If col.HeaderText = colHeaderText Then
            result = col.Index
            Exit For
        End If
    Next
    return result
End Function

然后在你的代码中:

For Each row As DataGridViewRow In grdTransaction.Rows
            If grdTransaction.Item(getColID("header text"), row.Index).Value IsNot Nothing Then
                If grdTransaction(getColID("header text"), row.Index).Value.Equals(DBNull.Value) Then
                    row.DefaultCellStyle.BackColor = Color.Red
                End If
            End If
        Next

或这个小小的改变:

For Each row As DataGridViewRow In grdTransaction.Rows
            If row.cells(getColID("header text")).Value IsNot Nothing Then
                If row.cells(getColID("header text")).Value.Equals(DBNull.Value) Then
                    row.DefaultCellStyle.BackColor = Color.Red
                End If
            End If
        Next

答案 2 :(得分:0)

我认为这很简单..

For Each row As DataGridViewRow In grdTransaction.Rows

    If Not IsDBNull(row.cells("column_name").Value) Then

        row.DefaultCellStyle.BackColor = Color.Red

    End If

 Next