选择单选按钮将打开具有所选图像的新表单

本文关键字:新表单 表单 图像 将打开 单选按钮 选择 | 更新日期: 2023-09-27 18:17:01

我有一个winform c#应用程序,用户可以在其中从各种RadioButton中进行选择,旁边有一个ImageBox。我想做的是,当选择RadioButton时,相同的图像会出现在另一个表单上以继续该过程。基本上,我需要的是将所选图像从formA中的picturebox1传输到formB中的picturebox2

我现在拥有的是:

private void button1_Click(object sender, EventArgs e)
{
    if (radioButton1.Checked)
    {
        build build = new build(); 
        build.ShowDialog();
    }  
    else if (radioButton2.Checked)
    {

这只打开具有PictureBox的表单build,其中我想从formA加载相同的图像。

感谢您的支持,

编辑:

我尝试了Mong Zhu的解决方案,但当我点击按钮时没有发生任何事情。如何在图片框中指示图片的显示位置?我的代码是:

FormA:

private void button1_Click(object sender, EventArgs e)
{
    if (radioButton1.Checked)
    {
        build build = new build (@"/Images/2C.png");

表格B:

public partial class build : Form
{
    string img = @"/Images/2C.png";
    public build(string img)
    {
        img = @"/Images/2C.png";
    }

编辑2:

再次感谢您的帮助,所以我使用了您的代码,但现在我得到了以下错误:

xxxx.exe中发生"System.NullReferenceException"类型的未处理异常附加信息:对象引用未设置为对象实例。

编辑3:

好的,所以,谢谢你的提示,代码前进了,但现在我得到了以下错误:

System.Windows.Forms.dll 中发生类型为"System.ArgumentException"的未处理异常

附加信息:路径上的字符无效。行中:

pictureBox2.Load(img_from_A);

我想这是因为我使用的路径,图像存储在项目的bin''images文件夹中,并添加到解决方案资源管理器中。

我使用的代码是:

 build build = new build("@|DataDirectory|/Images/JAF.jpg"); 

我也试过:

build build = new build("@../Images/JAF.jpg"); 

build build = new build("@/Images/JAF.jpg"); 

同样的错误。有任何建议,再次感谢。

选择单选按钮将打开具有所选图像的新表单

您基本上需要的是FormB中的一个字段,如:

string image_path;

然后,您可以重写构造函数,并在FormA:中调用窗体时将此路径传递给窗体

FormB formB = new FormB(image_path_from_formA);

构造函数将初始化字段,然后:

public FormB(string image_path_from_somewhere)
{
    image_path = image_path_from_somewhere;
}

现在您可以使用此路径将图像加载到FormBPictureBox

编辑:

我会尝试使用你的代码:

FormA:

private void button1_Click(object sender, EventArgs e)
{
    if (radioButton1.Checked)
    {
        build build = new build (@"/Images/2C.png");
    }
}

在FormB中,您可以存储路径以供以后使用,也可以立即加载图片:

public partial class build : Form
{
    // you don't need to initialize it. You will pass the right link
    // later through the constructor
    string img;
    public build(string img_from_A)
    {
        // store for later use
        img = img_from_A;
        // or load it right away
        pictureBox1.Load(img_from_A);
    }
}

编辑2:

请确保在InitializeComponent()调用后尝试访问构造函数中的任何元素:

public partial class build : Form
{
    // you don't need to initialize it. You will pass the right link
    // later through the constructor
    string img;
    public build(string img_from_A)
    {
        // First this has to happen!
        InitializeComponent();

        // store for later use
        img = img_from_A;
        // or load it right away
        pictureBox1.Load(img_from_A);
    }
}

编辑3:

如果您使用的是windows,并且您的图像位于bin'Images文件夹中,则应该使用反斜杠''而不是/,并使用以下行:

build build = new build("@..'Images'JAF.jpg");