如何使用打开文件对话框在另一个表单的图片框中加载图像

时间:2014-01-09 15:42:04

标签: c#

当我点击链接标签时,它应该打开一个对话框,可以选择一个JPEG图像文件,然后在另一个表格的图片框中打开。

这是我到目前为止的代码:

private void llblOpenSavedImages_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    {
        Open_Saved_Design_Form frm = new Open_Saved_Design_Form();
        frm.Show();
    }
}

3 个答案:

答案 0 :(得分:1)

将图像路径传递给另一个表单构造函数,如下所示:

 Open_Saved_Design_Form frm = new Open_Saved_Design_Form();
 frm.Show(ofd.FileName);

并在Open_Saved_Design_Form添加构造函数

private string imgPath;
public Open_Saved_Design_Form(string path)
{
    InitializeComponent();
    imgPath = path;
}

然后您可以在第二种形式中使用该路径。

答案 1 :(得分:1)

您需要将文件名从OpenFileDialog传递到新表单,如下所示:

private void llblOpenSavedImages_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    {
        if(!string.IsNullOrEmpty(ofd.FileName))
        {
            Open_Saved_Design_Form frm = new Open_Saved_Design_Form(ofd.FileName);
            frm.Show();
        }
    }
}

你的第二个表单的构造符应如下所示:

private string fileName;

public Open_Saved_Design_Form(string file)
{
    InitializeComponent();
    fileName = file;
}

然后在新表单的Load事件中,您将设置图像:

private void Open_Saved_Design_Form_Load(Object sender, EventArgs args)
{
    pictureBox.ImageLocation = fileName;
}

答案 2 :(得分:0)

表格1:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        if (!string.IsNullOrEmpty(dlg.FileName))
        {
            Form2 frm = new Form2(dlg.FileName);
            frm.Show();
        }
    }
}

表格2:

private string _imagePath;

public Form2(string imagePath)
{
    InitializeComponent();
    _imagePath = imagePath;
}

private void Form2_Load(object sender, EventArgs e)
{
    pictureBox1.ImageLocation = _imagePath;
}