日期:2014-05-18  浏览次数:20923 次

在winfrom中动态添加控件的问题!!!急!!!!!!!!
在按钮的单击事件中

                        PictureBox   picBox   =   new   PictureBox();
                        picBox.Width   =   260;
                        picBox.Height   =   80;
                        picBox.Left   =   20;
                        picBox.Top   =   20;              
                        panel1.Controls.Add(picBox);
                     
                        Graphics   myGrap   =   picBox.CreateGraphics();
                        Pen   blackPen   =   new   Pen(Color.Black,   3);
                        Point   point1   =   new   Point(100,   100);
                        Point   point2   =   new   Point(500,   100);
                        myGrap.DrawLine(blackPen,   point1,   point2);
为什么就显示不出来呢

------解决方案--------------------
panel1.Refresh();才是王道。。。
------解决方案--------------------
参考一下我的代码吧,不过是vb的语法,C#的我也不怎么会写,呵呵

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim pic As New PictureBox
With pic
.Location = New Point(100, 50)
.Size = New Size(200, 200)
.BorderStyle = BorderStyle.FixedSingle
End With
Me.Controls.Add(pic)
Dim g As Graphics = Me.GetGraphics(pic)
g.DrawLine(Pens.Red, New Point(0, 0), New Point(pic.Width, pic.Height))
End Sub

Function GetGraphics(ByRef pic As PictureBox) As Graphics
Dim bmp As Bitmap = New Bitmap(pic.Width, pic.Height)
pic.Image = bmp

Dim g As System.Drawing.Graphics = Graphics.FromImage(bmp)
Return g
End Function

End Class