Delete Image from Windows Form DataGridView and Folder (Directory) in C# and VB.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

how to delete image file from gridview and new folder in image remove using c# windows application

Posted 2 months ago

Hey pujandoshi,

Please refer below sample.

Namespaces

C#

using System.IO;
using System.Data;
using System.Data.SqlClient;

VB.Net

Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Code

C#

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.ColumnCount = 2;
    dataGridView1.Columns[0].Name = "Id";
    dataGridView1.Columns[0].HeaderText = "Id";
    dataGridView1.Columns[0].DataPropertyName = "Id";

    dataGridView1.Columns[1].HeaderText = "Name";
    dataGridView1.Columns[1].Name = "Name";
    dataGridView1.Columns[1].DataPropertyName = "Name";
    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;

    DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
    uninstallButtonColumn.Name = "Delete";
    uninstallButtonColumn.Text = "Delete";
    uninstallButtonColumn.UseColumnTextForButtonValue = true;
    dataGridView1.Columns.Add(deleteButtonColumn);
    this.BindDataGridView();

    dataGridView1.CellContentClick += new DataGridViewCellEventHandler(Delete);
}

private void BindDataGridView()
{
    string constr = @"Data Source=.\SQL2005;Initial Catalog=dbFiles;uid=sa;pwd=pass@123";
    using (SqlConnection conn = new SqlConnection(constr))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblFilesPath", conn))
        {
            DataTable dt = new DataTable();
            sda.Fill(dt);
            dt.Columns.Add("Data", Type.GetType("System.Byte[]"));
            foreach (DataRow row in dt.Rows)
            {
                row["Data"] = File.ReadAllBytes(row["Path"].ToString());
            }

            dataGridView1.DataSource = dt;
        }
    }
}

private void btnChoose_Click(object sender, EventArgs e)
{
    string saveDirectory = @"D:\Users\Ajeet\Images\";
    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);
            string constr = @"Data Source=.\SQL2005;Initial Catalog=dbFiles;uid=sa;pwd=pass@123";
            using (SqlConnection conn = new SqlConnection(constr))
            {
                string sql = "INSERT INTO tblFilesPath 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();
}

private void Delete(object sender, DataGridViewCellEventArgs e)
{
    string id = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 3].Value.ToString();
    string name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 2].Value.ToString();
    string constr = @"Data Source=.\SQL2005;Initial Catalog=dbFiles;uid=sa;pwd=pass@123";
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string sql = "DELETE FROM tblFilesPath WHERE Id = @Id";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            conn.Open();
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.ExecuteNonQuery();
            conn.Close();
            this.BindDataGridView();
            File.Delete(@"D:\Users\Ajeet\Images\" + name);
        }
    }
}

VB.Net

Public Sub New()
    InitializeComponent()
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    dataGridView1.AutoGenerateColumns = False
    dataGridView1.ColumnCount = 2
    dataGridView1.Columns(0).Name = "Id"
    dataGridView1.Columns(0).HeaderText = "Id"
    dataGridView1.Columns(0).DataPropertyName = "Id"
    dataGridView1.Columns(1).HeaderText = "Name"
    dataGridView1.Columns(1).Name = "Name"
    dataGridView1.Columns(1).DataPropertyName = "Name"
    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
    Dim deleteButtonColumn As DataGridViewButtonColumn = New DataGridViewButtonColumn()
    uninstallButtonColumn.Name = "Delete"
    uninstallButtonColumn.Text = "Delete"
    uninstallButtonColumn.UseColumnTextForButtonValue = True
    dataGridView1.Columns.Add(deleteButtonColumn)
    Me.BindDataGridView()
    AddHandler dataGridView1.CellContentClick, AddressOf Delete
End Sub

Private Sub BindDataGridView()
    Dim constr As String = "Data Source=.\SQL2005;Initial Catalog=dbFiles;uid=sa;pwd=pass@123"

    Using conn As SqlConnection = New SqlConnection(constr)

        Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM tblFilesPath", conn)
            Dim dt As DataTable = New DataTable()
            sda.Fill(dt)
            dt.Columns.Add("Data", Type.GetType("System.Byte[]"))

            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

Private Sub btnChoose_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim saveDirectory As String = "D:\Users\Ajeet\Images\"

    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)
            Dim constr As String = "Data Source=.\SQL2005;Initial Catalog=dbFiles;uid=sa;pwd=pass@123"

            Using conn As SqlConnection = New SqlConnection(constr)
                Dim sql As String = "INSERT INTO tblFilesPath 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
        End If
    End Using

    Me.BindDataGridView()
End Sub

Private Sub Delete(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
    Dim id As String = dataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex - 3).Value.ToString()
    Dim name As String = dataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex - 2).Value.ToString()
    Dim constr As String = "Data Source=.\SQL2005;Initial Catalog=dbFiles;uid=sa;pwd=pass@123"

    Using conn As SqlConnection = New SqlConnection(constr)
        Dim sql As String = "DELETE FROM tblFilesPath WHERE Id = @Id"

        Using cmd As SqlCommand = New SqlCommand(sql, conn)
            conn.Open()
            cmd.Parameters.AddWithValue("@Id", id)
            conn.Close()
            Me.BindDataGridView()
            File.Delete("D:\Users\Ajeet\Images\" & name)
        End Using
    End Using
End Sub

Screenshot