Hi, @Ben Ramsay ,Welcome to Microsoft Q&A,
Save the image to the 'DataGridView' cell and load and save it from the 'PictureBox' .
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Initialize DataGridView with an image column
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.HeaderText = "Image";
imageColumn.Name = "ImageColumn";
dataGridView1.Columns.Add(imageColumn);
}
private void btnLoadImage_Click(object sender, EventArgs e)
{
// Load image into PictureBox
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog.FileName);
}
}
private void btnSaveToDataGrid_Click(object sender, EventArgs e)
{
// Save image from PictureBox to DataGridView
if (pictureBox1.Image != null)
{
int rowIndex = dataGridView1.Rows.Add();
dataGridView1.Rows[rowIndex].Cells["ImageColumn"].Value = pictureBox1.Image;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Save DataGridView data when form is closing
SaveDataGridViewImages();
}
private void SaveDataGridViewImages()
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells["ImageColumn"].Value != null)
{
Image image = (Image)dataGridView1.Rows[i].Cells["ImageColumn"].Value;
string filePath = $"image_{i}.png"; // Save the image with a unique name
image.Save(filePath);
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.