Search code examples
vb.netexcelspreadsheetgear

"Open an existing file in Spreadsheetgear using VB.Net


I am trying to open an existing file in WorkBookView (named wkbMain in code given below) placed on my Windows Form. I am using the following code:

Private Sub MenuItemOpen_Click(sender As Object, e As EventArgs)
    Dim lObjDialog As New OpenFileDialog

    wkbMain.GetLock()

    Try
        If lObjDialog.ShowDialog() = DialogResult.OK Then
            wkbMain = SpreadsheetGear.Factory.GetWorkbook(lObjDialog.FileName, System.Globalization.CultureInfo.CurrentCulture)
        End If
    Catch ex As Exception

    Finally
        wkbMain.ReleaseLock()
    End Try
End Sub

But the assignment

wkbMain = SpreadsheetGear.Factory.GetWorkbook(lObjDialog.FileName, System.Globalization.CultureInfo.CurrentCulture)`) 

throws an exception:

Unable to cast object of type 'ᢷ' to type 'SpreadsheetGear.Windows.Forms.WorkbookView'.

Please suggest a solution


Solution

  • You need to set the WorkbookView.ActiveWorkbook property to the object returned by Factory.GetWorkbook(...), not on your WorkbookView object itself. Example:

    wkbMain.ActiveWorkbook = SpreadsheetGear.Factory.GetWorkbook(lObjDialog.FileName, 
        System.Globalization.CultureInfo.CurrentCulture))