Reputation: 33
How do I draw a line on a Panel that I just created in code? I am using my own class panel called MyPanel which the only difference between it and a regular panel is I give it a border. In my code this is what I got:
Dim newPanel as New MyPanel
dim graphicPanel as graphic = newPanel.createGraphic
graphicPanel.drawline(pens.Black, 20, 65,20,65)
basePanel.controls.add(newPanel)
The program is going to add several of these panels (which each one maybe a little different, and I want to just be able to draw some lines on them, in which I can modify later, or just clear and make new.
Since I am creating this panel in code, I can't access the _Paint event, which I assume is the reason the code above does work? Any Idea's?
Upvotes: 0
Views: 1595
Reputation: 18320
Your line is not shown because as soon as the panel is redrawn the line will not be included.
Of course you can access the panel's Paint
event, you would use the AddHandler statement to be able to subscribe to dynamically created controls' events.
Private Sub CreatePanel()
Dim newPanel As New MyPanel
AddHandler newPanel.Paint, AddressOf MyPanel_Paint
basePanel.Controls.Add(newPanel)
End Sub
Private Sub MyPanel_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs)
e.Graphics.DrawLine(Pens.Black, 20, 65, 20, 65)
End Sub
Upvotes: 0
Reputation: 742
CreateGraphics will always be "erased" as soon as the panel invalidates. If you use your own MyPanel class then you can just override the onPaint method of it and draw the line in that MyPanel class (if all of your MyPanels should have that Line).
Also as a note, if you create a control in code you can still access all it's events. For example in VB.NET you can Declare it global with the keyword WithEvents or you can use AddHandler to add eventhandler to your control.
Example:
Class MyPanel
Inherits Panel
Protected Overrides Sub OnPaint(e As PaintEventArgs)
MyBase.OnPaint(e)
e.Graphics.DrawLine(System.Drawing.Pens.Black, 0, 0, Me.Width, Me.Height)
e.Graphics.DrawLine(System.Drawing.Pens.Black, Me.Width, 0, 0, Me.Height)
End Sub
End Class
This example would draw 2 diagonal lines in the panel.
//Edited an example code in
Regards
Upvotes: 2