dataType checking question in VB.NET
I am trying to see if the datagrid.datasource is of a particular type then take different action.
if grid.datasource is CollectionBase then
' do sone thing
else if grid.datasource is IEnumerable then
' d开发者_如何学运维o other thing
end if
The first check gives me CollectionBase is a type and cannot be used a expression. What does that mean?
UPDATE 1:
I checked and it seems I am sending an array of objects to the grid. Something like Customers[]. How can I make it generic so I can get the array and also somehow get the count.
You need to use TypeOf … Is …
:
If TypeOf grid.datasource Is CollectionBase Then
' do sone thing
Else If TypeOf grid.datasource Is IEnumerable Then
' do other thing
End If
Merely using Is
checks for identity of two objects. However, the second operand in your code isn’t an object, it’s a type name.
try this
if grid.datasource.GetType() is GetType(CollectionBase) then
Dim myCollection as CollectionBase = TryCast(grid.DataSource, CollectionBase)
If (myCollection IsNot Nothing) Then
myCollection.Count
End If
else if grid.datasource.GetType() is GetType(IEnumerable) then
Dim myCollection as IEnumerable= TryCast(grid.DataSource, IEnumerable)
If (myCollection IsNot Nothing) Then
myCollection.Count()
End If
end if
精彩评论