简体   繁体   中英

Load image from path (DataGridView)

In my data table I have columns 'imgname' and 'imgpath', 'imgname' contains just the name of the image (ex. Test.pdf) and the 'imgpath' contains full image path to folder (ex. D:\PDF Archive\New folder\Test.pdf) where the File.Copy function stores uploaded images. I want to display the image with double click on datagridview row in new form (picturebox). Not completely sure how to write the code for it.

string source = Path.Combine(Environment.CurrentDirectory, fileName);
                string destin = @"D:\PDF Archive\New folder\";
                fileName = Path.GetFileName(fileName);


                if (!Directory.Exists(destin))
                {
                    Directory.CreateDirectory(destin);
                }

                File.Copy(source, destin + fileName, true);

// Code for inserting to Data Table

 CRUD.sql = "INSERT INTO archive(name, number, date1, date2, reciever, imgname, imgpath)" +
                                    " VALUES(@name, @number, @date1, @date2, @reciever, @imgname, @imgpath)";

                        execute(CRUD.sql, "Insert");

                        MessageBox.Show("Successfully added to Archive.", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

Could anyone provide me with an example code on how to display image from 'imgpath' to new form picturebox on doubleclick?

You say you want to display an image, but your file name (Test.PDF) suggests that you are working with a PDF file (Adobe Acrobat file). Displaying an Image in a picturebox is rather trivial, but displaying a PDF in a picturebox is not possible (anyone want to correct me?). There are third party tools to do that, or you could use a web browser control to do it. If you just want to display the PDF, but outside of your forms, you could do this in the cell double click event of the DataGridView (I am assuming the image path is in column 2):

private void dgvGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    using (System.Diagnostics.Process pProcess = new System.Diagnostics.Process())
    {
        string imgPath = dgvGrid.Rows[e.RowIndex].Cells[2].Value.ToString();
        pProcess.StartInfo.FileName = imgPath;
        pProcess.StartInfo.UseShellExecute = true;
        pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
        pProcess.Start();
    }
}

If you really just want to show an image in a picturebox when a row is double clicked, you can do it like this:

private void dgvGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    string imgPath = dgvGrid.Rows[e.RowIndex].Cells[2].Value.ToString();
    pictureBox1.Image = new Bitmap(imgPath);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM