1

我正在填充一个DataGridView,如下面的代码所示。但是,虽然每个创建的行都与创建列的 parent 相关联,但DataGridView我无法按列名引用行中的单元格。

有没有办法让我按列名引用?我宁愿避免使用基于整数的索引。

编辑:请注意,DataGridView 的列已使用 Visual Studio 设计器创建并正确命名。

Private Sub SetServiceOrders()
    Dim Row As DataGridViewRow = Nothing
    Dim RowValues As IServiceOrderDataGridViewRowValues = Nothing

    Me.ServiceOrdersDataGridView.Rows.Clear()
    If Not _ServiceOrders Is Nothing AndAlso _ServiceOrders.Count > 0 Then
        For Each ServiceOrder As ServiceOrder In _ServiceOrders.Values
            RowValues = ServiceOrder
            Row = New DataGridViewRow()
            Me.ServiceOrdersDataGridView.Rows.Add(Row)
            With Row
                'This Fails: "Specified argument was out of the range of valid values."
                .Cells("StatusImageColumn").Value = My.Resources.BulletGreen24
                .Cells("OrderDateColumn").Value = RowValues.Created
                .Cells("CreatedByColumn").Value = RowValues.OwnerName
            End With
            Me.ServiceOrdersDataGridView.Rows.Add()
        Next
    End If
End Sub
4

3 回答 3

3

您无法引用DataGridViewCell按列名称,因为DataGridViewRow未正确创建:

  Row = New DataGridViewRow() '=> new datagridview row with no knowledge about its DataGridView Parent
  Me.ServiceOrdersDataGridView.Rows.Add(Row) '

我相信这行:Me.ServiceOrdersDataGridView.Rows.Add(Row) 会将行与 DataGridView 相关联。

似乎没有。这应该起作用:

 Private Sub SetServiceOrders()
        Dim Row As DataGridViewRow = Nothing
        Dim RowValues As IServiceOrderDataGridViewRowValues = Nothing
        Dim rowIndex As Integer 'index of the row

        Me.ServiceOrdersDataGridView.Rows.Clear()
        If Not _ServiceOrders Is Nothing AndAlso _ServiceOrders.Count > 0 Then
            For Each ServiceOrder As ServiceOrder In _ServiceOrders.Values
                RowValues = ServiceOrder

                '/////Create a new row and get its index/////
                rowIndex = Me.ServiceOrdersDataGridView.Rows.Add() 

               '//////Get a reference to the new row ///////
                Row = Me.ServiceOrdersDataGridView.Rows(rowIndex) 

                With Row
                    'This won't fail since the columns exist 
                    .Cells("StatusImageColumn").Value = My.Resources.BulletGreen24
                    .Cells("OrderDateColumn").Value = RowValues.Created
                    .Cells("CreatedByColumn").Value = RowValues.OwnerName
                End With

                '//// I think this line is not required 
                ' Me.ServiceOrdersDataGridView.Rows.Add() 
            Next
        End If
    End Sub
于 2013-08-07T15:26:28.807 回答
1

Dim cellValue As String = DataGridView_Subjects.CurrentRow.DataBoundItem("columnName").ToString()

于 2018-01-26T14:30:47.173 回答
0

由于(似乎)您没有将 DataGridView 与数据对象本身绑定,因此您不应期望列名与数据对象属性相同。

在手动填充 DataGridView 中的数据之前,尝试设置相同的列名。

dataGridView1.Columns(0).Name = "StatusImageColumn" ' and so on
于 2013-08-07T11:15:04.683 回答