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?
精彩评论