Display image from filename in a database record to a datagridview - vb.net

I want to display the picture found in the file location that is in the field "Picture" I have this code that shows the fields in the datagridview but I cannot figure how to properly code image from file.
Update - this below code works fine
enter code here
Imports System.Data.OleDb
Public Class test
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub test_Load(sender As Object, e As EventArgs) Handles MyBase.Load
getthedata() ' this does a query and adds a column to the query data datatable
Filldatagrid() ' This fills the datagridview named DG1
End Sub
Sub getthedata()
sel = "select * from dog"
DataConnection()
cmd = New OleDbCommand(sel, con)
ds.Tables.Add(dt)
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim imageColumn As New DataColumn
imageColumn.ColumnName = "Picture"
imageColumn.DataType = GetType(System.Drawing.Image)
dt.Columns.Add(imageColumn)
For Each row As DataRow In dt.Rows
row("Picture") = System.Drawing.Image.FromFile(row("pic"))
Next
dt.AcceptChanges()
con.Close()
End Sub
Sub Filldatagrid()
dg1.AutoGenerateColumns = False
dg1.RowTemplate.Height = 150 ' this is the larger size to accomodate the image
dg1.ColumnCount = 4
dg1.DataSource = dt
dg1.Columns(0).DataPropertyName = "ID"
dg1.Columns(0).Visible = False
dg1.Columns(1).HeaderText = "Name"
dg1.Columns(1).DefaultCellStyle.Font = New Font("Tahoma", 15)
dg1.Columns(1).DefaultCellStyle.ForeColor = Color.DarkGreen
dg1.Columns(1).DataPropertyName = "Nam"
dg1.Columns(1).Width = 100
dg1.Columns(2).HeaderText = "Birthday"
dg1.Columns(2).DefaultCellStyle.Font = New Font("Tahoma", 15)
dg1.Columns(2).DataPropertyName = "Birth"
dg1.Columns(2).Width = 150
dg1.Columns(3).DataPropertyName = "Pic"
dg1.Columns(3).Visible = False
Dim dgvImageColumn As New DataGridViewImageColumn
dgvImageColumn.DataPropertyName = "Picture"
dgvImageColumn.Width = 150
dgvImageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom
dg1.Columns.Add(dgvImageColumn)
End Sub
End Class
The database records are:
Id Nam Birth Pic Comments
1 Brody 5/15/2015 C:\Users\JRS89\Dropbox\Photos\dogs\Brody\Brody.jpg
2 Bella 5/1/2015 C:\Users\JRS89\Dropbox\Photos\dogs\Bella\Bella.jpg
3 Benji 5/15/2016 C:\Users\JRS89\Dropbox\Photos\dogs\Benji\Benji.jpg

Related

DataGridView moves rows to bottom when cell is updated with Unbound data

I have a DataGridView that is styled with code and is using data from a SQLite Database
The Database is NOT bound to the DataGridView. A number of events are triggered when I click on a row.
First the Database is updated with today's date.
And the cell that contain's that date reflects the change.
I then call a sort on the column based on the cells value. With this code
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
The process works as expected with no issues IF I omit these lines of code from the Sub Routine ViewSearches() that populates the DataGridView.
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
I can use these empty rows if I make a call to repopulate the DataGridView with ViewSearches()
I am trying to avoid this design as it seems like a over use of resource.
The ERROR that is happening is the 4 rows that contain data are moved to the bottom of the DataGridView and above these 4 rows with data are the empty rows. I will post the relevant code below.
My question How can I keep the empty rows and populate DataGridView so the rows with data are at the top of the DataGridView?
Here is a Screen Shot after I selected LID 2. It is updated and bubbled to the bottom of the DGV.
Private Sub ViewSearches()
Dim intID As Integer
Dim strChannelName As String
Dim strLinkAddress As String
Dim strLastVisit As String
Dim strLinkType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
'Dim emptyStr As String = " "
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
'cmd.CommandText = "SELECT * FROM LinkTable"
' Line of CODE Above works with If statement in While rdr
'==========================================================
'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'News'"
cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSLT
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
'dgvLinks.DataSource = rdr
'Statement Above use when DB is bound to dgvLinks
'=================================================
While rdr.Read()
intID = CInt((rdr("LID")))
strChannelName = rdr("ytChannelName").ToString
strLinkAddress = rdr("ytLinkAddress").ToString
strLastVisit = rdr("ytLastVisit").ToString
strLinkType = rdr("ytSiteType").ToString
'If strLinkType = gvSLT Then
dgvLinks.Rows.Add(intID, strChannelName, strLinkAddress, strLastVisit)
rowCount = rowCount + 1
'End If
End While
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
End Using
End Using
'FindEmpty()
End Sub
Click Event with Update to Database
Private Sub dgvLinks_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvLinks.CellClick
selRow = e.RowIndex
If e.RowIndex = -1 Then
gvalertType = "4"
frmAlert.ShowDialog()
Exit Sub
End If
'Dim col As DataGridViewColumn = Me.dgvLinks.Columns(e.ColumnIndex)
Dim row As DataGridViewRow = Me.dgvLinks.Rows(e.RowIndex)
If row.Cells(2).Value Is Nothing Then
gvalertType = "5"
frmAlert.ShowDialog()
Return
Exit Sub
ElseIf gvTxType = "View" Then
webPAGE = row.Cells(2).Value.ToString()
siteID = CInt(row.Cells(0).Value.ToString())
UpdateSiteData()
''MsgBox("Stop " & selRow)
'dgvLinks.ClearSelection()
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
Process.Start(webPAGE)
'dgvLinks.Columns.Clear()
''dgvLinks.Rows.Clear()
''ViewSearches()
ElseIf gvTxType = "Delete" Or gvTxType = "Update" Then
gvID = CInt(row.Cells(0).Value)
gvSiteName = row.Cells(1).Value.ToString
gvSiteURL = row.Cells(2).Value.ToString
frmADE.Show()
Close()
End If
End Sub
Update Routine
Public Sub UpdateSiteData()
Dim dateToday = Date.Today
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytLastVisit = #ytLastVisit WHERE LID =" & siteID, conn)
conn.Open()
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.ExecuteNonQuery()
dgvLinks.Rows(selRow).Cells(3).Value = dateToday.ToString("M-d-yyyy")
'Line of code above INSERTS value in Last Visit Column at the correct ROW
'NOT needed if you reload data from the database
'=========================================================================
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
End Sub
You will see a number of things I have tried commented out.
As I said I can FIX the issue if I make a call to the ViewSearches() Sub Routine.
Private Sub StyleDGV()
'Sets Design of the DataGridView
'===============================
dgvLinks.DefaultCellStyle.Font = New Font("Times New Roman", 13.0F, FontStyle.Bold)
dgvLinks.ColumnCount = 4
dgvLinks.Columns(0).Width = 60 'ID
dgvLinks.Columns(1).Width = 325 'Site Name 325
dgvLinks.Columns(2).Width = 860 'Site Url 860
dgvLinks.Columns(3).Width = 154 'LastVisit 140
'Option with no blank rows increase col count to 5
'OR increase width of col(3) WHY? because the scroll bar is not showing
' TOTAL Width 1450 Height 488
'=============================
'To Set Col Header Size Mode = Enabled
'To Set Col Header Default Cell Styles DO in Properties
'dgvLinks.Columns(6).DefaultCellStyle.Format = "c"
dgvLinks.ColumnHeadersHeight = 10 'Sans Serif 'Tahoma
dgvLinks.ColumnHeadersDefaultCellStyle.Font = New Font("Sans Serif", 12.0F, FontStyle.Bold)
dgvLinks.ColumnHeadersDefaultCellStyle.ForeColor = Color.Blue
dgvLinks.DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
'DGV Header Names
dgvLinks.Columns(0).Name = "LID"
dgvLinks.Columns(1).Name = "Site Name"
dgvLinks.Columns(2).Name = "Site URL"
dgvLinks.Columns(3).Name = "Last Visit"
dgvLinks.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(3).SortMode = DataGridViewColumnSortMode.NotSortable
End Sub
Any one following this question the FIX that permitted keeping the empty rows was to just omit the sort command in the Update to Database Sub Routine
As far as getting the data from the SQLite DB into the grid… you almost have it in the ViewSearches method. The command text looks good; however you are using an SQLiteDataReader. This is resorting to reading the data line by line.
I suggest you use the SQLiteDataAdapter instead. With it you can get the DataTable from the DB in one shot. First create and initialize a DataSet, then create a new SQLiteDataAdapter then add your command to the data adapter something like…
DataSet ds = new DataSet();
using (SQLiteDataAdapter sqlDA = new SQLiteDataAdapter()) {
conn.Open();
sqlDA.SelectCommand = cmd.CommanText;
sqlDA.Fill(ds, “tableName”);
if (ds.Tables.Count > 0) {
//return ds.Tables[“tableName”];
dgvLinks.DataSource = ds.Tables[“tableName”];
}
}
This will add a DataTable to the DataSet ds called “tableName” if the query succeeded.
Then simply use that DataTable as a DataSource to the grid… something like…
dgvLinks.DataSource = ds.Tables[“tableName”];

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

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.

Highlight a row in Datagridview based on textbox value

Good Evening.
I have a program in VB.Net that refreshes datagridview after you edit some data my problem here is im populating over 1000 records.
Let say Im editing row 999 and after i click update the data will refresh causing the datagridview to return at the top (The blue highlighter)
My goal here is how can I maintain it to its current position after update?
My solution here is highlight the data where Textbox1 = value
Is this possible like this?
'SAMPLE CODE
Datagridview1.Column(0).value.BlueHighLighter = Textbox1.text
Pls see my code on how i refresh DGV
Dim con11 As MySqlConnection = New MySqlConnection("server=192.168.2.87;userid=root;password=admin1950;database=inventory")
Dim sql1 As MySqlCommand = New MySqlCommand("select PONo,ItemCode,Description,QtyPack,PackUoM,QtyStan,StanUoM,UnitPrice,Total,Remarks,ExpiryDate from Receiving where RINo = '" & Add_Receiving_Items.TextBox1.Text & "';", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
Add_Receiving_Items.DataGridView1.DataSource = ds1.Tables(0)
con1.close()
With Add_Receiving_Items.DataGridView1()
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "PO No"
.Columns(1).HeaderCell.Value = "Item Code"
.Columns(2).HeaderCell.Value = "Description"
.Columns(3).HeaderCell.Value = "Quantity/Pack"
.Columns(4).HeaderCell.Value = "Packaging UoM"
.Columns(5).HeaderCell.Value = "Quantity/Pc"
.Columns(6).HeaderCell.Value = "Standard UoM"
.Columns(7).HeaderCell.Value = "Unit Price"
.Columns(8).HeaderCell.Value = "Total"
.Columns(9).HeaderCell.Value = "Remarks"
.Columns(10).HeaderCell.Value = "Expiry Date"
End With
Add_Receiving_Items.DataGridView1.Columns.Item(0).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(1).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(2).Width = 120
Add_Receiving_Items.DataGridView1.Columns.Item(3).Width = 86
Add_Receiving_Items.DataGridView1.Columns.Item(4).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(5).Width = 75
Add_Receiving_Items.DataGridView1.Columns.Item(6).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(7).Width = 70
Add_Receiving_Items.DataGridView1.Columns.Item(8).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(9).Width = 105
Add_Receiving_Items.DataGridView1.Columns.Item(10).Width = 63
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
With Add_Receiving_Items.DataGridView1
.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke
.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender
End With
TYSM for future help
Use DataGridView.CurrentRow property. But please be aware that CurrentRow is ReadOnly, you must use CurrentCell
Before refreshing your data store Dim oldIndex = DataGridView.CurrentRow.Index and after the refresh set DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)
EDIT:
How to test the Code
Create a form with a Button1 and a DataGridView1 with two columns and paste the following code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 5
DataGridView1.Rows.Add("foo" & i, "bar" & i)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentIndex = DataGridView1.CurrentRow.Index
currentIndex += 1
If currentIndex >= DataGridView1.Rows.Count Then currentIndex = 0
DataGridView1.CurrentCell = DataGridView1.Rows(currentIndex).Cells(0)
End Sub
End Class
EDIT:
Dim oldIndex = DataGridView.CurrentRow.Index
'Put your code here on how you refresh your data
DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)

How to change row color in datagridview by comparing two columns from different tables using vb.net?

No success!
If user of tblcon with billmonth of tbltrns exists in tbltrns then highlight the rows of tblcon with red color
Code:
Private Sub checkexist()
For Each row As DataGridViewRow In DataGridView1.Rows
ConObj = New SqlConnection(ConStr)
ConObj.Open()
Dim qry As String = "SELECT * FROM tblTrns WHERE userName=#userName and bill_month=#bill_month"
CmdObj = New SqlCommand(qry, ConObj)
CmdObj.Parameters.AddWithValue("#bill_month", DateTimePicker1.Text)
CmdObj.Parameters.AddWithValue("#userName", (row.Cells("User").Value.ToString))
drObj = CmdObj.ExecuteReader()
If drObj.HasRows Then
row.DefaultCellStyle.BackColor = Color.Red
End If
Next
ConObj.Close()
End Sub
Query for the Grid
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],connectionstatus[Status] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
Query Changed in getdata but no success. Please guide ...........................................................................................................................................................................................................................................
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],conn‌​‌​‌​ectionstatus[Status], (SELECT ISNULL(COUNT(*), 0) FROM tblTrns WHERE tblTrns.userName = tblCon.UserName AND bill_month = '" & DateTimePicker1.Text & "') [Comparison] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
I recommend you to fill a new column in your grid with a value for comparison and set it's visibility to false.
You can do that by a subselect or a left join on the second table (if you wish an example just post the query that fills your grid).
Based on your comparison column you can use the CellPainting event of the GridView. Like this:
Private Sub grdGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles grdGridView.CellPainting
If e.RowIndex >= 0 Then
If grdGridView.Rows(e.RowIndex).Cells("colComparison").Value <> "0" And Not IsNothing(grdGridView.Rows(e.RowIndex).Cells("colComparison").Value) Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.SelectionBackColor = Color.IndianRed
End If
End If
End Sub