额,我刚学c#不久额,问下哈
现在有这么个类drawbackground的draw方法用来画15x15的格子,然后我要在form1的paint事件里调用这个方法。
从未对字段“123.drawbackground.g”赋值,字段将一直保持其默认值 null。报这个错额。最好能回答问题的说后多说一下Graphics g这个东西,个人感觉不是很理解.
    
    class drawbackground
    {
        private static Graphics g;
        private static Pen p = new Pen(Color.Black);//定一个黑色画笔
     
        public static void draw()
        {            for (int x = 0; x < 15; x++)
            {
                for (int y = 0; y < 15; y++)
                {
                    g.DrawLine(p,x, y * 40, 600, y *40);//横线
                    g.DrawLine(p, x * 40, y, x * 40, 600);//竖线                }
            }
        }
    }form1里调用的    private void Form1_Paint(object sender, PaintEventArgs e)
        {
            drawbackground.draw();
        }

解决方案 »

  1.   


        class drawbackground
        {
            private Graphics g;
            private Pen p = new Pen(Color.Black);//定一个黑色画笔        public drawbackground(Graphics graphics)
            {
                g = graphics;
            }        public void draw()
            {
                for (int x = 0; x < 15; x++)
                {
                    for (int y = 0; y < 15; y++)
                    {
                        g.DrawLine(p, x, y * 40, 600, y * 40);//横线
                        g.DrawLine(p, x * 40, y, x * 40, 600);//竖线                }
                }
            }
        }        private void Form1_Paint(object sender, PaintEventArgs e)
            {
                Graphics g = this.CreateGraphics();
                drawbackground dbg = new drawbackground(g);
                dbg.draw();
            }
      

  2.   

    Control类及其子类(即运行期间界面上可见的控件),都可以使用CreateGraphics()方法创建默认的画布对象,然后可以运行Graphics的相关方法进行绘制了,在进行相关操作的时候,需要注意刷新的问题。