这个问题已经困扰我一段时间了,因为它很容易修复,但并不理想。
我有一个有 5 列的 DataGridView。第一个称为 ID。
在 vb.net 中,以下行给出错误“对象引用未设置为对象的实例”:
dgvJobs.Columns("ID").Visible = False ' ERROR
dgvJobs.Columns(0).Visible = False ' OK
显然,使用名称比使用硬编码值来引用列要好得多,但想知道我是否可以做些什么来使其正常工作?
datagridview 数据源是 BindingSource 控件,数据源是数据集。
编辑:根据答案,我创建了以下函数,该函数完全符合我的需要:
Private Function GetColName(ByVal name As String, ByRef dgv As DataGridView) As Integer
Dim retVal As Integer
For Each col As DataGridViewColumn In dgv.Columns
If col.HeaderText = name Then
retVal = col.Index
Exit For
End If
Next
Return retVal
End Function
用途:
dgvJobs.Columns(GetColName("ID", dgvJobs)).Visible = False
最佳答案
两个提示:
1- 默认情况下,Winforms 设计器在表单类中为 DataGridView 中存在的每个列创建一个对象。因此,例如,如果您有一个名为 MyIdColumn 的列,您应该能够在表单代码中访问该列,如下所示:
Me.MyIdColumn.Visible = False
如果你想访问 DataGridView 的元素,你可以这样做:
Dim value = dgv.Item(MyIdColumn.Index, rowIndex).Value
使用此技巧,如果列名称发生更改,也不会出现问题,因为您直接引用该列,而不是表示可能更改的列名称的字符串。
2- 您的 GetColName 方法可能会更好;我会将其转换为扩展方法:
<System.Runtime.CompilerServices.Extension()> _
Private Function GetColByHeaderText(ByVal dgv As DataGridView, ByVal name As String) As DataGridViewColumn
For Each col As DataGridViewColumn In dgv.Columns
If col.HeaderText = name Then
Return col
End If
Next
Return Nothing
End Function
用法:
dgv.GetColByHeaderText("ID").Visible = False
在我看来好多了!
关于.net - DataGridView.Column(ColumnName as String)给出错误 "Object reference not set to an instance of an object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2021665/