In this article I will explain with an example, how to save Image in Folder (Directory) and Path in Database in Windows Forms Application using C# and VB.Net.
The Images saved in Folder (Directory) will be displayed using DataGridView control in Windows Forms Application using C# and VB.Net.
Database
This article makes use of a table named Files whose schema is defined as follows.
Note: You can download the database table SQL by clicking the download link below.
Form Design
The below Form consists of a Button and a DataGridView control.
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Displaying Images using Path stored in database in DataGridView
Inside the Form Load event handler, columns are added to the DataGridView control.
The first two columns are normal Text columns while the third column is a DataGridViewImage column which is specially meant for displaying Images.
The records from the Database Table are fetched into a DataTable. The DataTable consists of the Path of the Image file and DataGridView cannot display Image using its Path.
Hence a new column named Data is created and using For Loop, each Image file is read and converted into a Byte Array and is copied to the Data column.
Finally the DataTable is used to populate the DataGridView control.
C#
private void Form1_Load(object sender, EventArgs e)
{
//Set AutoGenerateColumns False.
dataGridView1.AutoGenerateColumns = false;
//Set Columns Count.
dataGridView1.ColumnCount = 2;
//Add Columns.
dataGridView1.Columns[0].Name = "Id";
dataGridView1.Columns[0].HeaderText = "Image Id";
dataGridView1.Columns[0].DataPropertyName = "FileId";
dataGridView1.Columns[1].HeaderText = "Name";
dataGridView1.Columns[1].Name = "Name";
dataGridView1.Columns[1].DataPropertyName = "Name";
//Add a Image Column to the DataGridView at the third position.
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.Name = "Image";
imageColumn.DataPropertyName = "Data";
imageColumn.HeaderText = "Image";
imageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
dataGridView1.Columns.Insert(2, imageColumn);
dataGridView1.RowTemplate.Height = 100;
dataGridView1.Columns[2].Width = 100;
//Bind DataGridView.
this.BindDataGridView();
}
private void BindDataGridView()
{
string constr = @"Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Files", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
//Add a new Byte[] Column.
dt.Columns.Add("Data", Type.GetType("System.Byte[]"));
//Convert all Images to Byte[] and copy to DataTable.
foreach (DataRow row in dt.Rows)
{
row["Data"] = File.ReadAllBytes(row["Path"].ToString());
}
dataGridView1.DataSource = dt;
}
}
}
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Set AutoGenerateColumns False.
dataGridView1.AutoGenerateColumns = False
'Set Columns Count.
dataGridView1.ColumnCount = 2
'Add Columns.
dataGridView1.Columns(0).Name = "Id"
dataGridView1.Columns(0).HeaderText = "Image Id"
dataGridView1.Columns(0).DataPropertyName = "FileId"
dataGridView1.Columns(1).HeaderText = "Name"
dataGridView1.Columns(1).Name = "Name"
dataGridView1.Columns(1).DataPropertyName = "Name"
'Add a Image Column to the DataGridView at the third position.
Dim imageColumn As DataGridViewImageColumn = New DataGridViewImageColumn()
imageColumn.Name = "Image"
imageColumn.DataPropertyName = "Data"
imageColumn.HeaderText = "Image"
imageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch
dataGridView1.Columns.Insert(2, imageColumn)
dataGridView1.RowTemplate.Height = 100
dataGridView1.Columns(2).Width = 100
'Bind DataGridView.
Me.BindDataGridView()
End Sub
Private Sub BindDataGridView()
Dim constr As String = "Data Source=.\SQL2014;Initial Catalog= AjaxSamples;Integrated Security=true"
Using conn As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Files", conn)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Add a new Byte[] Column.
dt.Columns.Add("Data", Type.[GetType]("System.Byte[]"))
'Convert all Images to Byte[] and copy to DataTable.
For Each row As DataRow In dt.Rows
row("Data") = File.ReadAllBytes(row("Path").ToString())
Next
dataGridView1.DataSource = dt
End Using
End Using
End Sub
Saving Image in Folder (Directory) and Path in Database in Windows Application
The following event handler gets called when the Choose File Button is clicked and an Image file is selected.
The uploaded Image file is saved into a Folder (Directory) on disk and its Path is inserted into the database table.
C#
private void btnChoose_Click(object sender, EventArgs e)
{
string saveDirectory = @"D:\SavedImages\";
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
string fileName = Path.GetFileName(openFileDialog1.FileName);
string fileSavePath = Path.Combine(saveDirectory, fileName);
File.Copy(openFileDialog1.FileName, fileSavePath, true);
string constr = @"Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO Files VALUES(@Name, @Path)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(fileName));
cmd.Parameters.AddWithValue("@Path", fileSavePath);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
this.BindDataGridView();
}
}
}
VB.Net
Private Sub btnChoose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnChoose.Click
Dim saveDirectory As String = "D:\SavedImages\"
Using openFileDialog1 As OpenFileDialog = New OpenFileDialog()
If openFileDialog1.ShowDialog() = DialogResult.OK Then
If Not Directory.Exists(saveDirectory) Then
Directory.CreateDirectory(saveDirectory)
End If
Dim fileName As String = Path.GetFileName(openFileDialog1.FileName)
Dim fileSavePath As String = Path.Combine(saveDirectory, fileName)
File.Copy(openFileDialog1.FileName, fileSavePath, True)
Dim constr As String = "Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true"
Using conn As SqlConnection = New SqlConnection(constr)
Dim sql As String = "INSERT INTO Files VALUES(@Name, @Path)"
Using cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(fileName))
cmd.Parameters.AddWithValue("@Path", fileSavePath)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Me.BindDataGridView()
End If
End Using
End Sub
Screenshot
Downloads