In this tutorial, I will teach you how to display and resize the image in the datagridview using access database and visual basic.net. This sample project will help you to display the image from the access database to the datagridview. It also has the capability to fit the displayed image in the datagridview according to the column width and row height. Follow the step by step guide to know how it works. Hope this project will help your current problem.
Open Microsoft Visual Studio 2015 and create a new windows form application in visual basic.
Do the form just like shown below.
Press F7 to open the code editor. In the code editor, add a namespace for
OLeDB to access
OLeDB libraries .
- Imports System.Data.OleDb
Create a connection between the access database and c#. After that, declare all the classes and variables that are needed.
- Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\dbsaveimg.accdb")
- Dim cmd As OleDbCommand
- Dim da As OleDbDataAdapter
- Dim dt As DataTable
- Dim sql As String
Create a method for retrieving images in the database.
- Private Sub loadData(sql As String, dtg As DataGridView)
- cmd = New OleDbCommand
- da = New OleDbDataAdapter
- dt = New DataTable
- With cmd
- .Connection = con
- .CommandText = sql
- End With
- da.SelectCommand = cmd
- dtg.DataSource = dt
- dtg.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
- Catch ex As Exception
- End Try
- End Sub
Write the following code for resizing the image in displaying in the datagridview.
- Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
- If (e.RowIndex < 0 Or e.ColumnIndex < 0) Then Return
- If DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ValueType = GetType(Byte()) Then
- DataGridViewImageCell).ImageLayout = DataGridViewImageCellLayout.Zoom
- End If
- End Subssss
Do the following code for displaying the image in the datagridview when the form is loaded.
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- sql = "Select img as Picture From tblimage"
- loadData(sql, DataGridView1)
- End Subs
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.