Answer the question
In order to leave comments, you need to log in
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")
System.NullReferenceException: "Ссылка на объект не указывает на экземпляр объекта."
Answer the question
In order to leave comments, you need to log in
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question