Rabu, 01 Februari 2012

Show Image To PictureBox From DatagridView Or DataReader

Sudah aga lama saya tidak posting, lumayan sibuk.... langsung saja ya, bagaimana cara menampilkan image/gambar dari DataGridView ke PictureBox atau langsung dari DataReader ke PictureBox. Jawabannya sangat sederhana jika kita tahu caranya...hehe. Lihatlah contohnya pada gambar dibawah ini:
Kalau mau praktek, siapkan 1 project, 1 form, 1datagridview (name=djieDatagriView1), 1 picturebox (name=djiePictureBox1), saya menggunakan database northwind sqlserver.

Di form load kita koneksikan ke database dan load data ke datagridview :

Dim CON As New Odbc.OdbcConnection

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CON.ConnectionString = String.Format("DRIVER={0};SERVER={1};DATABASE={2};TRUSTED_CONNECTION=YES", "SQL SERVER NATIVE CLIENT 10.0", "DJIESOFT\SQL2008", "NORTHWIND")
CON.Open()

Dim ADP As New Odbc.OdbcDataAdapter("SELECT FIRSTNAME,PHOTO FROM EMPLOYEES", CON)
Dim DT As New DataTable
ADP.Fill(DT)
djieDataGridView1.DataSource = DT
End Sub

Selanjutnya simpan function yang sudah saya buat ini (mau di form atau di module, bebas) :

Public Function djieGetDataToImage(ByVal pData As Byte()) As Drawing.Image
Try
Dim imgConverter As New System.Drawing.ImageConverter()
Return TryCast(imgConverter.ConvertFrom(pData), Drawing.Image)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return Nothing
End Try
End Function

Nah, ini implementasi pada saat datagridview di click :

Private Sub djieDataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles djieDataGridView1.CellClick
djiePictureBox1.Image = djieGetDataToImage(djieDataGridView1.CurrentRow.Cells(1).Value)
End Sub

Jika ingin menggunakan DataReader, artinya memilih photo-nya langsung dari table, seperti ini contoh implementasinya :

Private Sub djieDataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles djieDataGridView1.CellClick
Dim CMD As New Odbc.OdbcCommand("SELECT PHOTO FROM EMPLOYEES WHERE FIRSTNAME='" + djieDataGridView1.CurrentRow.Cells(0).Value.ToString + "'", CON)
Dim RD As Odbc.OdbcDataReader = CMD.ExecuteReader
If RD.Read Then
djiePictureBox1.Image = djieGetDataToImage(RD.Item("PHOTO"))
End If
RD.Close()
End Sub

Selamat mencoba, semoga sukses !

Tags:
Show image to picture box, datagridview to picturebox, picturebox from datagridview, set image from datagridview, set image from datareader, get image from datagridview, get image from datareader, datareader to picturebox, visual basic net, c#, visual studio, example, source code

Ditulis Oleh : Wahyu Aji // 02.21
Kategori:

1 komentar: