V
V
Vladimir Zuev2021-03-25 20:55:09
Visual Basic
Vladimir Zuev, 2021-03-25 20:55:09

How to display an image on a button in a loop?

vb.net I'm trying to put pictures on buttons in a cycle.

Me.Controls("Button" & (i + 16)).BackgroundImage = LoadImageFromFile("Фигуры\" & i & ".jpg")

Error pops up
System.NullReferenceException: "Ссылка на объект не указывает на экземпляр объекта."

How to write code correctly so that there is no such error. Please help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BasiC2k, 2021-03-26
@BasiC2k

1. It is better to load a picture in the code once, and not 16 times.
Dim oBitmap As Bitmap = New Bitmap("Shapes\" & i & ".jpg")
2. Before assigning a picture to a button, it would be nice to check if there is such a button. Therefore:
Dim oButton as Button
For i As Integer = 0 To 16
oButton = Me.Controls("Button" & (i))
If IsNothing(oButton) Then Continue For ' There is no such button
oButton.BackgroundImage = oBitmap
next

V
Vladimir Zuev, 2021-03-26
@vladd56

Hello.
Thanks for the help. The fact is that I have 12 buttons on the TabControl tab. And 12 pictures in the Shapes folder. And the first button on this tab is Button17. Therefore, in the loop, I tried this entry Me.Controls("Button" & (i + 16)). Wrote this code

Dim i As Integer
        Dim oButton As Button
        For i = 1 To 12
            Dim oBitmap As Bitmap = New Bitmap("Фигуры\" & i & ".jpg")
            oButton = Me.Controls("Button" & (i + 16))
            If IsNothing(oButton) Then Continue For ' Такой кнопки нет
            oButton.BackgroundImage = oBitmap
        Next i

But the pictures on the buttons did not receive. Apparently it is necessary to take into account that the buttons are on the TabControl tab. How to do it right? Please help.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question