Col Mortimer
Col Mortimer

Reputation: 1

Writing to Labels sequentially in VB.Net

Apologies, this is probably a very simple problem, due to me stumbling through basic without any tuition....

I am trying to display cells from an excel file in labels attached to a table. I can manipulate the excel file OK and I can do it if I use text boxes.

For example, using text boxes (this is an extract):

Imports System.Reflection
Imports Excel = Microsoft.Office.Interop.Excel   

Public Class Form1

    Dim APP As New Excel.Application
    Dim worksheet As Excel.Worksheet
    Dim workbook As Excel.Workbook
    Dim excelfilepath As String = AppDomain.CurrentDomain.BaseDirectory
    Dim n As Integer = 0

    Private Sub Form7_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        workbook = APP.Workbooks.Open(excelfilepath & "mydata.xlsx")
        worksheet = workbook.Worksheets("sheet1")
        APP.Visible = False

        For n = 1 To 10
            Me.Controls("textbox" & n).Text = DirectCast(worksheet.Cells(1, n),   Excel.Range).Value.ToString
        Next
    End Sub
End Class

The above works fine. However, if I substitute the textbox line in the for/next loop with:

Me.Controls("label" & n).Text = DirectCast(worksheet.Cells(1, n - 1), Excel.Range).Value.ToString

I get an unhandled exception "object reference not set to an instance of an object"

Writing to a single label, thus:

Label16.Text = DirectCast(worksheet.Cells(1, n - 1), Excel.Range).Value.ToString

works just fine.

What am I doing wrong?

Upvotes: 0

Views: 63

Answers (0)

Related Questions