开发者

Invalidate() causes NULL POINTER exception on programmatically addedd control (c#)

开发者 https://www.devze.com 2023-03-28 03:20 出处:网络
When I add a PictureBox to my form like this: public partial class frmMain : Form { PictureBox _pb; public formMain(){

When I add a PictureBox to my form like this:

public partial class frmMain : Form
{
    PictureBox _pb;

    public formMain(){

    _pb = new PictureBox();
    formMain.Controls.Add(_pb);
    }

    //SOME METHOD
    private void SomeMethod(){
        _pb.Invalidate();  //NULL POINTER EXCEPTION
    }
}

What's going on here? Is more needed to add a control to a form?

More info:

If I drag a picturebox to the "form designer"开发者_JS百科 in visual studio C#, and name it _pb.

The above works. Are there additional steps to adding a control programmatically? More than just calling Form.Controls.Add(/some control/) ???


Really just a hunch, would need to see the full class and not just pieces of it. But one curiosity is that you have:

formMain.Controls.Add

in a constructor for formMain, where is the variable formMain defined (assuming this compiles). Don't you mean:

this.Controls.Add(_pb)

Not sure if this the problem, I suspect that the problem could also be that _pb is not defined by the time that it invalidate is called. Do you have any other constructors that are used that don't initialized _pb?

0

精彩评论

暂无评论...
验证码 换一张
取 消