我试图将这个图片框创建为另一个类别的另一个表单时遇到麻烦,我希望我已经提供了足够的信息c:
Catelogue.cs< - 加载图片框的类
class Catelogue
{
public void loadCatelogue()
{
mainPageGUI u = new mainPageGUI();
PictureBox pictureBox1 = new PictureBox();
pictureBox1.Location = new System.Drawing.Point(0, 0);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new System.Drawing.Size(500, 500);
pictureBox1.BackColor = Color.Red;
u.Controls.Add(pictureBox1);
MessageBox.Show("HI");
}
}
mainmenuGUI.cs< ---表示调用loadcatelogue()加载图片框
private void catelogueButton_Click(object sender, EventArgs e)
{
Catelogue a = new Catelogue();
a.loadCatelogue();
}
答案 0 :(得分:1)
您正在创建mainPageGUI表单的新实例,并向该实例添加新的图片框。此实例不是调用您的方法的实例,它永远不会显示。因此,您的原始实例保持不变,您没有看到任何内容。 (只是为了演示问题尝试用 u.Show(); )来改变你的MessageBox行
要修复,只需更改您的调用代码并传递应在其上创建图片框的表单实例
private void catelogueButton_Click(object sender, EventArgs e)
{
Catelogue a = new Catelogue();
// pass this instance to the method....
a.loadCatelogue(this);
}
当然使用传递的实例
public void loadCatelogue(mainPageGUI u)
{
PictureBox pictureBox1 = new PictureBox();
pictureBox1.Location = new System.Drawing.Point(0, 0);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new System.Drawing.Size(500, 500);
pictureBox1.BackColor = Color.Red;
u.Controls.Add(pictureBox1);
}