问题描述
我正在填充 DataGridView
,如下面的代码所示。但是,尽管每个创建的行都与在其中创建列的父 DataGridView
关联,但是我无法按列名引用该行中的单元格。
I'm populating a DataGridView
as shown in the code below. However while each created row is associated with the parent DataGridView
, in which the columns are created, I cannot reference cells in the row by column name.
是否可以通过列名引用?我宁愿避免使用基于整数的索引。
Is there a way for me to reference by column name? I would rather avoid using the integer based index.
EDIT :请注意,DataGridView的列已创建,并使用Visual正确命名。 Studio设计人员。
EDIT: note that the columns of the DataGridView has been created and correctly named using the Visual Studio designer.
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
推荐答案
您无法引用 DataGridViewCell
列名,因为未正确创建 DataGridViewRow
:
You are not able to reference the DataGridViewCell
by column name because the DataGridViewRow
is not correctly created:
Row = New DataGridViewRow() '=> new datagridview row with no knowledge about its DataGridView Parent
Me.ServiceOrdersDataGridView.Rows.Add(Row) '
似乎没有。应改为:
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
这篇关于如何通过DataGridViewRow中的列名引用DataGridViewCell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!