datagridview Image Display vb.net MS Access - vb.net

my code is to read the image file path in every row and display it in the datagridview "Image" Column.
.....
what's the problem with my code? please help me fix this.
UPDATE
this is the updated code but it displays nothing.
Dim dbdataset As New DataTable
Try
con.Open()
query = "Select * FROM [svfmemberlist]"
cmd = New OleDbCommand(query, con)
da.SelectCommand = cmd
da.Fill(dbdataset)
dgvSearch.RowTemplate.Height = 150
source.DataSource = dbdataset
dgvSearch.DataSource = source
Dim img As New DataGridViewImageColumn()
dgvSearch.Columns.Add(img)
img.HeaderText = "Image"
img.Name = "img"
img.ImageLayout = DataGridViewImageCellLayout.Zoom
dgvSearch.Columns("img").DataGridView.AutoGenerateColumns = False
dgvSearch.Columns("Name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
dgvSearch.Columns("img").Width = 150
For Each row As DataGridViewRow In dgvSearch.Rows
If Not row.Cells("imgPath").FormattedValue.ToString = Nothing Then
Dim str As String = row.Cells("imgPath").FormattedValue.ToString
Dim inImg As Image = Image.FromFile(str)
row.Cells("img").Value = inImg
Else
img.Image = Nothing
End If
Next
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

The following example does not match how you are loading data and images but with a little effort will work within your current code.
I created two columns in the DataGridView via the IDE, one Text and one Image DataGridViewColumn.
The first line in form load sets ImageLayout, second line of code sets alignment to top-left for appearances. Next I set auto-size mode for all columns followed by setting the row height for each row.
Next (these lines are to load images from a folder one level below the app folder).
Setup the path to the images.
Add images using FileImageBytes function (which I would place into a separate class or code module but works just fine in your form).
Yes everything is hard-wired so it's easy to see how everything works.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CType(DataGridView1.Columns("PictureColumn"), DataGridViewImageColumn).ImageLayout = DataGridViewImageCellLayout.Normal
DataGridView1.Columns.Cast(Of DataGridViewColumn).Select(Function(col) col).ToList _
.ForEach(Sub(col) col.CellTemplate.Style.Alignment = DataGridViewContentAlignment.TopLeft)
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
DataGridView1.RowTemplate.Height = 222
Dim imagePath As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images")
DataGridView1.Rows.Add(New Object() {"Car1", FileImageBytes(IO.Path.Combine(imagePath, "Car1.bmp"))})
DataGridView1.Rows.Add(New Object() {"Car2", FileImageBytes(IO.Path.Combine(imagePath, "Car2.jpg"))})
End Sub
Public Function FileImageBytes(ByVal FileName As String) As Byte()
Dim fileStream As IO.FileStream = New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim byteArray(CInt(fileStream.Length - 1)) As Byte
fileStream.Read(byteArray, 0, CInt(fileStream.Length))
Return byteArray
End Function
End Class

Related

Display image in Datagridview

I am trying to display image in datagridview using ms-access and vb.net 2012.
my database in store image path does not image directly so when try to retrieve image in datagridview it shows the image path, not the image.
so how can I fix it?
Private Sub design_list_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Design_managementDataSet.design_details' table. You can move, or remove it, as needed.
'Me.Design_detailsTableAdapter.Fill(Me.Design_managementDataSet.design_details)
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Design Management\Database\design_management.accdb"
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
designDatagridShow()
End Sub
Private Sub designDatagridShow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("select * from design_details", cnn)
da.Fill(dt)
design_datagridview.AutoGenerateColumns = False
Dim ColImage As New DataGridViewImageColumn
Dim Img As New DataGridViewImageCell
design_datagridview.ColumnCount = 3
design_datagridview.Columns(0).Name = "design_number"
design_datagridview.Columns(0).HeaderText = "Design Number"
design_datagridview.Columns(0).DataPropertyName = "design_number"
design_datagridview.Columns(1).Name = "design_collection"
design_datagridview.Columns(1).HeaderText = "Design Collection"
design_datagridview.Columns(1).DataPropertyName = "design_collection"
design_datagridview.Columns(2).Name = "price"
design_datagridview.Columns(2).HeaderText = "Design Price"
design_datagridview.Columns(2).DataPropertyName = "price"
design_datagridview.Columns(3).Name = "design_image"
design_datagridview.Columns(3).HeaderText = "Design Image"
design_datagridview.Columns(3).DataPropertyName = "design_image"
design_datagridview.DataSource = dt
Dim value As String
value = design_datagridview.Columns(3).HeaderText = "design_image"
Label1.Text = value
cnn.Close()
End Sub
Update 1:
Thanks.
Add another column that is of System.Drawing.Image datatype, then set the image based on your image column's path using System.Drawing.Image.FromFile(...) like the following:
Dim imageColumn As New DataColumn
imageColumn.ColumnName = "ActualImage"
imageColumn.DataType = GetType(System.Drawing.Image)
dt.Columns.Add(ImageColumn)
For Each row As DataRow in dt.Rows
row("ActualImage") = System.Drawing.Image.FromFile(row("design_image"))
Next
dt.AcceptChanges()
Dim dgvImageColumn As New DataGridViewImageColumn
dgvImageColumn.DataPropertyName = "ActualImage"
dgvImageColumn.Name = "ActualImage"
dgvImageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom
design_datagridview.Columns.Add(dgvImageColumn)
design_datagridview.DataSource = dt

How to get values from variable in a private sub or make public variable that does not lose value

I am planning to create a project in the near future about quizzes and now I am practising some codes and this is my problem. I have a variable inside a private sub Button_Click. All variables work fine but I can't access it in other Private sub Button3_Click because it was a private variable so I decided it to make them a public variable.
Then when I ran it, it's only shows the last item on my database and I get back my original code and all the data in the database are shown and I create an event from my radiobutton when I checked it's automatically INSERT a data into my table. So I need the variable label but I can't access it in my event.
Note: All my controls are add programmatically when the database has a data except for panel1, button2 and button3.
This is my original code:
'This is for adding controls like labels and radiobutton dependeng in a number of data from database
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim conn As OleDbConnection = GetDBConnection()
Dim cmd As New OleDbCommand("SELECT * FROM tblEcobags ORDER BY N ASC", conn)
cmd.Prepare()
Dim dataReader As OleDbDataReader = cmd.ExecuteReader()
Do While dataReader.Read
Dim Cpanel As New Panel()
Dim count As Integer = Panel1.Controls.OfType(Of Panel)().ToList().Count
count = Panel1.Controls.OfType(Of Panel)().ToList().Count
Cpanel.Location = New Point(10, (25 * count) * 2.2)
Cpanel.Size = New Size(537, 51)
Cpanel.Name = "Cpanel" & (count + 1)
Cpanel.BackColor = Color.White
Panel1.Controls.Add(Cpanel)
Dim label As New Label()
count = Cpanel.Controls.OfType(Of Label)().ToList().Count
label.Location = New Point(10, (25 * count))
label.AutoSize = True
label.Name = "label_" & (count + 1)
label.Text = dataReader.Item("N") & "."
label.Font = New Font(label.Font.FontFamily, 10, FontStyle.Bold)
Cpanel.Controls.Add(label)
Dim lblQ As New Label()
count = Cpanel.Controls.OfType(Of TextBox)().ToList().Count
lblQ.Location = New System.Drawing.Point(40, 25 * count)
lblQ.AutoSize = True
lblQ.Name = "lblQ" & (count + 1)
lblQ.Text = dataReader.Item("ProductDes")
lblQ.Font = New Font(lblQ.Font.FontFamily, 11)
Cpanel.Controls.Add(lblQ)
Dim rbChoiceA As New RadioButton()
count = Cpanel.Controls.OfType(Of RadioButton)().ToList().Count
rbChoiceA.Location = New Point(40, 25)
rbChoiceA.AutoSize = True
rbChoiceA.Name = "rb" & (count + 1)
rbChoiceA.Text = dataReader.Item("Each")
rbChoiceA.Font = New Font(rbChoiceA.Font.FontFamily, 10)
AddHandler rbChoiceA.CheckedChanged, AddressOf rbChoiceA_Checked
Cpanel.Controls.Add(rbChoiceA)
Dim rbChoiceB As New RadioButton()
count = Cpanel.Controls.OfType(Of RadioButton)().ToList().Count
rbChoiceB.Location = New Point(200, 25)
rbChoiceB.AutoSize = True
rbChoiceB.Name = "rb" & (count + 1)
rbChoiceB.Text = dataReader.Item("PerDozen")
rbChoiceB.Font = New Font(rbChoiceB.Font.FontFamily, 10)
Cpanel.Controls.Add(rbChoiceB)
Loop
Button2.Enabled = False
conn.Dispose()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'this is an event that i can't access my "label" that I add programmatically
Private Sub rbChoiceA_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim conn As OleDbConnection = GetDBConnection()
Dim cmd As New OleDbCommand("INSERT INTO tblSubmit(N)VALUES('" & must be label.text & "') ", conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You can set Variable as static in database or Text file or SQL or in program
like string myvar = "static";
Sorry for my bad description but I got it worked now. I used to declare it outside from any function but my mistakes that I made is declaring variable with parenthesis, I don't know the difference between that so I need to know the one without parenthesis works.
This is my modified declaration so It must be accessible to any function
Dim label as Label()
I got error on my updating code inside an event for my button2_Click
label = new label() ' I got error here
But when I removed the parenthesis on my declaration, it works.
Dim label as label
so may I ask what's the difference between that, why the one I used is no work than below that was worked. Thanks in advance for the respose.

Datagridview CheckboxColumn Shaded or (X) Mark when unchecked

Good Morning
I have a column in DataGridView that generates checkbox and in relation to that I have also a lot of columns in my table that is called 2016,2017 and so on and all of that is TinyInt
Now here is the image for both of them:
Now here is my question, instead of uncheck how can make it shaded or X mark in the DataGridView Column?
here is my code in populating the DataGridView:
Dim sql1 As MySqlCommand = New MySqlCommand("Select * from period_closure", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
ds1.Tables(0).Columns(2).DataType = GetType(Boolean)
Me.DataGridView1.Columns(0).Frozen = True
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next
DataGridView1.Columns("PeriodID").Visible = False
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.LightBlue
First of all download 'X' image in google, or create your own.
then try to add this in your code.
Private Sub CheckBox1_Paint(sender As Object, e As PaintEventArgs) Handles CheckBox1.Paint
If CheckBox1.Checked = False Then
Try
Dim newImage As Image = Image.FromFile("E:\Projects\Library\BER-X.jpg")
Dim x As Single = 0
Dim y As Single = 0
Dim width As Single = CheckBox1.Width 'You can also try this CheckBox1.Width - 3
Dim height As Single = CheckBox1.Height 'You can also try this CheckBox1.Height - 3
e.Graphics.DrawImage(newImage, x, y, width, height)
Catch ex As Exception
End Try
End If
End Sub
the X mark in the checkbox is not accurate in the position but you can fix it by your self. Try it and Explore it to fit it in your system. :)
Hope this will help you.

Display an image from datagridview to a picturebox

Can anyone help me with this one? The scenario is that when I click any columns in a datagridview it will display the image to a picturebox
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
lblProperty.Text = row.Cells("Column1").Value.ToString
txtType.Text = row.Cells("Column2").Value.ToString
txtPrice.Text = row.Cells("Column3").Value.ToString
txtBed.Text = row.Cells("Column4").Value.ToString
txtBath.Text = row.Cells("Column5").Value.ToString
txtFootages.Text = row.Cells("Column6").Value.ToString
txtStatus.Text = row.Cells("Column7").Value.ToString
txtYear.Text = row.Cells("Column8").Value.ToString
txtDesc.Text = row.Cells("Column9").Value.ToString
Dim bytes As [Byte]() = row.Cells("Column10").Value
Dim ms As New MemoryStream(bytes)
pbImage.Image = Image.FromStream(ms)
txtDate.Text = row.Cells("Column11").Value.ToString
txtAddress.Text = row.Cells("Column12").Value.ToString
txtStories.Text = row.Cells("Column13").Value.ToString
End If
End Sub
It has an error Unable to cast object of type 'System.String' to type 'System.Byte[]'.
Dim bytes As Byte() = Datagridview1.CurrentRow.Cells(5).Value
Using ms As New MemoryStream(bytes)
Picturebox1.Image = Image.FromStream(ms)
End Using
Maybe you are over thinking it, there is a function to easily draw bitmaps.
I would suggest using the DrawToBitmap on the DataGridView by using the ColumnBounds
example this:
Dim GridBitmap as new Bitmap(DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false).width,DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false).height)
DataGridView1.DrawToBitmap(GridBitmap,DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false))
pbImage.Image = GridBitmap
It might need to be adapted to your DataGridView.
Note, Instead of this:
Dim bytes As [Byte]() = row.Cells("Column10").Value
Dim ms As New MemoryStream(bytes)
pbImage.Image = Image.FromStream(ms)
Still having problem? Try this:
New project.
Add a DataGridView (DataGridView1) to your form.
Add some random columns to your gridview.
Add a Picture Box to your form (PictureBox1)
Make sure the Picture box property "SizeMode" is set to auto size.
Add an event forDataGridView1.MouseDown.
Add this code to the event.
Dim GridBitmap As New Bitmap(DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Width + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Left, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Height)
Dim GridColRectangle As New Rectangle(0, 0, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Width + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Left, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Height + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Top)
DataGridView1.DrawToBitmap(GridBitmap, GridColRectangle)
PictureBox1.Image = GridBitmap
You may need to adjust it to your own application.

Combobox selected Item does not match with its selected

I faced with that issue which appears with spaces after letters finished more than Combobox.SelectedItem's length. Why? How can I fix this issue?
Below is showing my issue as visual its a very short and small video.
Here is a small video
Imports System.Data.SqlClient
Public Class Main
WithEvents bsData As New BindingSource
Dim sConn As New SqlConnection
Dim dt As New DataTable
Dim ds As New DataSet
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sConn.ConnectionString = "Data Source=PC-N39;Initial Catalog=Esi01;Persist Security Info=True;User ID=sa;Password=sas"
sConn.Open()
Try
Dim myTable As DataTable = New DataTable("MyTable")
myTable.Columns.Add(New DataColumn("Group Code"))
myTable.Columns.Add(New DataColumn("Description"))
myTable.Columns.Add(New DataColumn("NothingSerious"))
Dim cmd As New SqlCommand("Select * from tbUnit", sConn)
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.Default)
Dim myRow As DataRow
While dr.Read()
myRow = myTable.NewRow
myRow.Item(0) = dr(0)
myRow.Item(1) = dr(1)
myRow.Item(2) = dr(2)
myTable.Rows.Add(myRow)
End While
dr.Close()
Dim myData4 As DataTable = myTable
ds = New DataSet()
ds.Tables.Add(myData4)
MultiColumnCombo1.DisplayMember = "Group Code"
MultiColumnCombo1.DrawMode = DrawMode.OwnerDrawVariable
MultiColumnCombo1.ColumnWidths = "50;150"
MultiColumnCombo1.DataSource = myData4
MultiColumnCombo1.Text = String.Empty
Catch ex As Exception
MsgBox(ex.ToString)
End Try
sConn.Close()
End Sub
End Class
What type is MultiColumnCombo1 ? I suppose it's a third party component.
As far as I can see in your video, it seems that it takes the biggest element in your data, take it's length and add spaces to other elements to make them the same size.
You probably won't be able to change the component's behavior, but you can apply the same logic to what you enter in your TextBox : adding spaces to make them match. Or if you simply need to make a condition that test if they are equal, you can do as follow :
if(YourComboboxSelectedItem.Trim() == StringYourAreComparingItTo)
See String.Trim(), that will discard the extra whitespaces.