这个
link
在Mick on的评论中
我的行动让我走上了我所希望的道路——这比我最初设想的要多出几步。
我最终得到的是一个
DataGridViewRow
.它在新的扩展功能中添加了一个
GetCellByColumnCaption
,它正是这样做的:它返回一个
DataGridViewCell
对象,该对象对应于
DataGridView
控制
这样做可以避免控件名成为问题。现在,我可以简单地通过新行中最可见的标识符来引用单元格:列标题文本。
下面是一个有效的例子。。。
Public Class Form1
Private Sub Form1_Load( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) _
Handles Me.Load
'Remove the new blank row.
dgv.AllowUserToAddRows = False
End Sub
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) _
Handles Button1.Click
Dim newRowIdx As Integer = dgv.Rows.Add()
Dim newRowObj As DataGridViewRow = dgv.Rows.Item(newRowIdx)
newRowObj.GetCellByColumnCaption("ID").Value = "123"
newRowObj.GetCellByColumnCaption("Name").Value = "Bob"
newRowObj.GetCellByColumnCaption("Etc").Value = "Red"
End Sub
End Class
Module ClassExtensions
'Note: The Extension() attribute requires .Net 3.5 or above.
<System.Runtime.CompilerServices.Extension()> _
Friend Function GetCellByColumnCaption( _
ByVal dgvr As DataGridViewRow, _
ByVal colCaption As String _
) _
As DataGridViewCell
For Each cell As DataGridViewCell In dgvr.Cells
Dim hdrText = LCase(cell.OwningColumn.HeaderText)
colCaption = LCase(colCaption)
If hdrText = colCaption Then
GetCellByColumnCaption = cell
Exit Function
End If
Next
GetCellByColumnCaption = Nothing
End Function
End Module