簡體   English   中英

如何使用打開文件對話框將圖像加載到其他表單的圖片框中

[英]how do I load an image in a picture box of another form using open file dialog

當我單擊鏈接標簽時,它應該打開一個對話框,可以選擇一個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();
    }
}

只需將圖像路徑傳遞給另一個表單構造函數,如下所示:

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

然后,您可以在第二種形式中使用該路徑。

您將需要將文件名從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;
}

表格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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM