In order to load the UserControl on runtime, I will create a button to trigger this. I could do it on Form_Load but for this example, I'll make it on the Button_Click.
I have the following files:
- Form1.vb
- UserControl1.vb
Form1.vb
In my Form1.vb
I have a TableLayoutPanel (used for resizing the controls). In the first row of my TableLayoutPanel I have a button which notifies the user to "Load User Control". The second row is a place holder for my UserControl.
The following code simply adds in the UserControl1 that I created into my TableLayoutPanel
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim ucColors As New UserControl1 'Create a new instance of the UserControl
ucColors.Dock = DockStyle.Fill 'Make it dock to it's parent container (this tablelayoutpanel)
TableLayoutPanel1.Controls.Add(ucColors, 0, 1) 'Add the control to the tablelayoutpanel
End Sub
End Class
UserControl1.vb
This is my UserControl1.vb. I created a TableLayoutPanel in this UserControl and docked it (fill). This makes the TableLayoutPanel resize to the size of the UserControl. I created three rows because you had three rows in your example.
This is the only code I need to paint the UserControl>TableLayoutPanels>Rows.
Public Class UserControl1
Private Sub TableLayoutPanel1_CellPaint(sender As Object, e As TableLayoutCellPaintEventArgs) Handles TableLayoutPanel1.CellPaint
Select Case e.Row
Case 0 'Row 1
e.Graphics.FillRectangle(Brushes.Orange, e.CellBounds)
Case 1 'Row 2
e.Graphics.FillRectangle(Brushes.Green, e.CellBounds)
Case 2 'Row 3
e.Graphics.FillRectangle(Brushes.Yellow, e.CellBounds)
End Select
End Sub
End Class
RunTime
When I execute my program, the Form1 pops up:
And then when I press the Load button, this occurs:
So, when I clicked on my button, a new instance of the user control was created which made it execute the Cell_Paint in the UserControl.
Hopefully this clears things up!