john doe
john doe

Reputation: 9670

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 
' do 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.

Upvotes: 0

Views: 2765

Answers (2)

Jay
Jay

Reputation: 6294

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

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545953

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.

Upvotes: 1

Related Questions