我正在填充DataGridView
,如下面的代码所示。但是,虽然每个创建的行都与创建列的父DataGridView
相关联,但我无法按列名引用行中的单元格。
我有没有办法按列名引用?我宁愿避免使用基于整数的索引。
编辑:请注意,已使用Visual Studio设计器创建并正确命名了DataGridView的列。
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
答案 0 :(得分:2)
您无法按列名称引用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
答案 1 :(得分:1)
Dim cellValue As String = DataGridView_Subjects.CurrentRow.DataBoundItem("columnName").ToString()
答案 2 :(得分:0)
由于(似乎)您没有将DataGridView与数据对象本身绑定,因此您不应期望列名与数据对象属性相同。
在手动填充DataGridView中的数据之前,请尝试设置相同的列名。
dataGridView1.Columns(0).Name = "StatusImageColumn" ' and so on