How to Display and Resize the Image in the DataGridView Using Access Database and VB.Net
Submitted by janobe on Thursday, July 18, 2019 - 22:28.
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.
Download the complete source code and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below
Creating an Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application in visual basic.Step 2
Do the form just like shown below.Step 3
Press F7 to open the code editor. In the code editor, add a namespace forOLeDB
to access OLeDB
libraries .
- Imports System.Data.OleDb
Step 4
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
Step 5
Create a method for retrieving images in the database.- Private Sub loadData(sql As String, dtg As DataGridView)
- Try
- con.Open()
- cmd = New OleDbCommand
- da = New OleDbDataAdapter
- dt = New DataTable
- With cmd
- .Connection = con
- .CommandText = sql
- End With
- da.SelectCommand = cmd
- da.Fill(dt)
- dtg.DataSource = dt
- dtg.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
- End Sub
Step 6
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
- CType(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex),
- DataGridViewImageCell).ImageLayout = DataGridViewImageCellLayout.Zoom
- End If
- End Subssss
Step 7
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
Add new comment
- 3032 views