从另一个类动态创建一个图片框到一个表单中 [英] Dynamically creating a picturebox from another class into a form

查看:32
本文介绍了从另一个类动态创建一个图片框到一个表单中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试将图片框创建为另一个类的另一种形式时遇到问题,我希望我提供了足够的信息 c:

I'm having troubles with this part trying to create a picturebox into another form from another class, i hope I've provided enough information c:

Catelogue.cs <-- 加载图片框的类

Catelogue.cs <-- class that loads the picturebox

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() 加载图片框的表单

mainmenuGUI.cs < --- form that's calling loadcatelogue() to load picturebox

private void catelogueButton_Click(object sender, EventArgs e)
{
    Catelogue a = new Catelogue();
    a.loadCatelogue();
}

推荐答案

您正在创建 mainPageGUI 窗体的一个新实例,并向该实例添加新的图片框.此实例不是调用您的方法的实例,它从未显示过.所以你的原始实例保持不变,你什么也看不到.(只是为了演示问题,尝试使用 u.Show(); 更改 MessageBox 行)

You are creating a new instance of the mainPageGUI form and add, to that instance, the new picturebox. This instance is not the one that calls your method and it is never showed. So your original instance remain unchanged and you don't see anything. (Just to demonstrate the problem try to change your MessageBox line with u.Show();)

要修复,只需更改您的调用代码并传递应在其上创建图片框的表单实例

To fix, just change your calling code and pass the form instance on which the picturebox should be created

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);
}

这篇关于从另一个类动态创建一个图片框到一个表单中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆