Reputation: 474
Given an existing DataGrid called grid.
When I try to access grid.Columns("column_name")
I get an exception
Column not found, column_name
I tried
If Not IsNull(grid.Columns("column_name")) Then '...
but I still get the exception.
I would like something which I could call like
grid.ContainsColumn("column_name")
Upvotes: 1
Views: 855
Reputation: 993
The columns in a DataGrid only have a caption text to identify what the column is so you could use something like this to check if the column exists by looking for a column with a Caption that matches the column name you are looking for.
Private Function DataGrid_CheckColumnExists(dataGrid As dataGrid, columnName As String)
Dim columnCount As Long, columnIndex As Long
Dim checkColumnName As String
columnCount = dataGrid.Columns.Count
For columnIndex = 0 To columnCount - 1
checkColumnName = dataGrid.Columns(columnIndex).Caption
DataGrid_CheckColumnExists = (StrComp(checkColumnName, columnName, vbTextCompare) = 0)
If DataGrid_CheckColumnExists Then Exit Function 'No need to continue once we found it
Next columnIndex
End Function
Upvotes: 3