How To Display Image Into Devexpress GridView / Devexpress Card View From Mysql - mysql

Here I would like to ask, how to display the image data into DevExpress DevExpress gridview or CardView.
For I will take a picture of data from mysql database that I keep with BLOB data type.
how or its code if using visual basic.?
for Code that I use:
Dim Query As String = "SELECT FTO.ALM_NIM as FOTO_ID, FTO.ALM_FOTO as FOTO FROM tbl_foto_alumni as FTO"
Using DA As New MySql.Data.MySqlClient.MySqlDataAdapter(Query, MyKonection)
Dim DTwisda As New DataTable
DA.Fill(DTwisda)
if Dtwisda.Rows.Count > 0 Then
GridControl.Datasource = DTwisda
MainView = CardView1
Dim RepItemImg As New Repository.RepositoryItemPictureEdit()
RepItemImg.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch
RepItemImg.BestFitWidth = 100
RepItemImg.CustomHeight = 150
With CardView1.Columns("FOTO")
.ColumnEdit = RepItemImg
End With
With CardView1
.OptionsBehavior.FieldAutoHeight = True
.MaximumCardRows = 2
.MaximumCardColumns = 6
End With
End If
End Using
To Screnshoot my program and the results of calling the data from the database, Please Check The Attachment.
already I attach the following word file.
ScreenShoot_Program
Please Help and Give The Solution.
Regards,
Tafary

Try This Code:
Dim row As DataRow
Dim i As Integer
For Each row In myDt.Rows
Column = New DataColumn
With Column
.DataType = GetType(Bitmap)
' .DefaultValue = Base64ToImage(row("Photo"))
.Unique = False
.ColumnName = "EmpPhoto"
End With
If Not myDt.Columns.Contains("EmpPhoto") Then
myDt.Columns.Add(Column)
End If
myDt.Rows(i)("EmpPhoto") = Base64ToImage(row("Photo"))
i += 1
myDt.AcceptChanges()
Next
i = 0
'myDt.Rows.Add(Column.DefaultValue)
Public Function Base64ToImage(base64String As String) As Image
Try
' Convert Base64 String to byte[]
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image1 As Image = Image.FromStream(ms, True)
Return image1
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function

Related

Remove duplicated rows on gridview

Hi There I have the following grid view developed with vb.net and html
This is the code to fill the gridview
Private Sub BindGrid()
Dim modelo As String = txtModelo.Text
Dim linha As String = txtLinha.Text
Dim data As String = txtData.Text
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM tempo where timermodelo = #timermodelo and timerlinha = #timerlinha and timerdata = #timerdata")
Using sda As New MySqlDataAdapter()
cmd.Parameters.AddWithValue("#timermodelo", modelo)
cmd.Parameters.AddWithValue("#timerlinha", linha)
cmd.Parameters.AddWithValue("#timerdata", data)
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End Sub
My question is, is it possible to remove the duplicated rows on the column Operador, Posto, Linha and Modelo?
And also how can I form the date to show 'dd-mm-yyyy'?
Actually, I want to merge these values, if they are the same, show just one time
Sorry if it is difficult to understand, if more information is needed let me know
Thanks in advance
Remove duplicates : Why don't you use SqlStatement that return rows without duplication, depending on your Database type 'you did not mention', if this is achievable in your SqlStatement then this problem is solved.
Format Date in GridView1 cell : Use GridView1_CellFormatting event [ Where your Date ColumnIndex = 4] as follows
Private Sub GridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
If Not IsNothing(e.Value) Then
If e.ColumnIndex().ToString = 4 And IsDate(e.Value) Then
e.Value = Format(e.Value, "dd-mm-yyyy")
End If
End If
End Sub
I want to merge these values, if they are the same
What values are we talking about here ?

VB.NET ComboBox SelectedIndex from MySQL

so I have done with show data form my database MySQL to ComboBox.. I'm using this code:
Private Sub Get_Product()
Connection()
Dim command As New MySqlCommand
Dim reader As MySqlDataReader
Dim query As String = "SELECT * FROM product, writer, publisher WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND code = " & throwCode & " ORDER BY code"
Dim queryWriter As String = "SELECT DISTINCT writer, writer_name FROM writer ORDER BY writer_name"
Dim dataAdapter As New MySqlDataAdapter(queryWriter, conn)
Dim dataSet As New DataSet
dataAdapter.Fill(dataSet, "writer")
Try
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
While reader.Read
TextBoxISBN.Text = reader("isbn")
TextBoxTitle.Text = reader("title")
TextBoxPage.Text = reader("page")
With (ComboBoxWriter)
.Items.Add("Select")
.DataSource = dataSet.Tables("writer")
.DisplayMember = "writer_name"
.ValueMember = "writer"
.SelectedIndex = 0 **// Give atention to this code**
End With
TextBoxYear.Text = reader("year")
TextBoxCategory.Text = reader("category")
TextBoxCallNumber.Text = reader("call_number")
TextBoxWeight.Text = reader("weight")
TextBoxPurchasePrice.Text = reader("purchase_price")
TextBoxSellingPrice.Text = reader("selling_price")
TextBoxDiscount.Text = reader("discount")
TextBoxDescription.Text = reader("description")
TextBoxTag.Text = reader("tag")
TextBoxPusatPenerbit.Text = reader("pusat_penerbit")
TextBoxMrican.Text = reader("mrican")
TextBoxPaingan.Text = reader("paingan")
If (Not IsDBNull(reader("picture"))) Then
Dim byteImage() As Byte = reader("picture")
Dim tempImage As New System.IO.MemoryStream(byteImage)
PictureBoxPicture.Image = Image.FromStream(tempImage)
End If
End While
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
In my code, I give some comment and bold to show you what I want to do.
So I have a writer code in product an writer code in writer (writer code named as writer), and I join the table to show writer name from writer code. But in ComboBox I want to show all of writer for editing but the default value is index of the writer that same like in product table.
1
2
If you see my first image that have a writer name Sutarjo Adisusilo but when I view it and want to use it as a default value in combobox that show A. Kardiyat Wiharyanto as indexvalue number 0..
I need help how to change the default value to be same like the picture number 1
Thanks
I've updated this answer to an easier method. Double check the column names though.
ComboBoxWriter.SelectedIndex = ComboBoxWriter.FindStringExact(reader("writer_name"))

Not able to open email attachment from bytes array

I am trying to attach a binary data retrieved from MySQL server to an email as attachment using VB.net.
I can send out a email with attachment but not able to open any of the attachment file even word file also is empty.
The error message is --> Adobe Reader could not open "xxx.pdf" because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).
Been googled around but still not able to find out what is wrong with my code.
Anyone can help will be very appreciated!Thanks!
Dim m_ImageBinary As [Byte]() = New [Byte](-1) {}
Dim m_AttachmentType As String = ""
Dim m_AttachmentName As String = ""
Dim m_Attachment As Boolean = False
Dim cmd3 As New MySqlCommand("SELECT Attachment, AttachmentType, AttachmentName FROM tbcommunication WHERE CommunicationID = " & cid, MySql)
Dim rdr2 As MySqlDataReader = cmd3.ExecuteReader()
While rdr2.Read()
If rdr2("Attachment").ToString() <> "" Then
Dim m_Length As Integer = DirectCast(rdr2("Attachment"), [Byte]()).Length
m_ImageBinary = New [Byte](m_Length - 1) {}
m_ImageBinary = DirectCast(rdr2("Attachment"), [Byte]())
m_AttachmentType = rdr2("AttachmentType").ToString()
m_AttachmentName = rdr2("AttachmentName").ToString()
End If
End While
If m_ImageBinary.Length <> 0 Then
If m_Attachment = False Then
If m_AttachmentType.Contains("jpeg") OrElse m_AttachmentType.Contains("bmp") OrElse m_AttachmentType.Contains("gif") Then
m_Attachment = False
Else
m_Attachment = True
End If
End If
If m_Attachment = True Then
' If not image file
Response.AppendHeader("content-disposition", "attachment; filename=" & m_Atta`enter code here`chmentName)
End If
'Write(binary)
'Response.ContentType = m_AttachmentType
'Response.BinaryWrite(m_ImageBinary)
'Response.[End]()
End If
Dim mailmssg As New MailMessage()
Dim smtp_client As New SmtpClient
Using memoryStream As New MemoryStream()
Dim bytes As Byte() = memoryStream.ToArray()
Dim att As New Attachment(New MemoryStream(bytes), m_AttachmentName)
mailmssg.Attachments.Add(att)
MemoryStream.Dispose()
smtp_client.DeliveryMethod = SmtpDeliveryMethod.Network
smtp_client.Send(mailmssg)
End Using
'...
' memoryStream = new blank MemoryStream
Using memoryStream As New MemoryStream()
' get emtpy array from memoryStream
Dim bytes As Byte() = memoryStream.ToArray()
' Create empty MemoryStream from empty bytes array
Dim att As New Attachment(New MemoryStream(bytes), m_AttachmentName)
'...
With your current code you'll never send anything than an empty file with a name and always only one.

Export Gridview connected to MYSQL data to excel

I have a simple form created in Visual Studio (VB) which has a data gridview connected to a table in MySQL (hosted in a remote server).
I have the below code to export the grid view to Excel but it takes a really long time to export (around 15 minutes).
The table in MySQL is really small (1000 rows and 60 columns).
Is there a better way to export the complete MySQL table to excel?
PLEASE HELP
CODE:
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.Rows.Count - 1
For j = 0 To DataGridView1.Columns.Count - 1
For k As Integer = 1 To DataGridView1.Columns.Count
On Error Resume Next
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next
xlWorkSheet.SaveAs("C:\Users\USERNAME\Desktop\vbexcel.xlsx")
xlWorkBook.Close()
Is there two ways to do this :
using rdlc reports.
using gridview exporting.
first way you need to created rdlc report, then retrieving data into datatable, then call this code:
Dim MyDataSource As ReportDataSource = New ReportDataSource("ReportDataSet", MyDataTable)
reportviewer1.LocalReport.ReportPath = Server.MapPath("MyrdlcReportPath")
rvSmartCardsIssues.LocalReport.EnableExternalImages = True
rvSmartCardsIssues.LocalReport.DataSources.Clear()
rvSmartCardsIssues.LocalReport.DataSources.Add(MyDataSource )
rvSmartCardsIssues.LocalReport.Refresh()
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
bytes = rvSmartCardsIssues.LocalReport.Render("Excel", Nothing, mimeType, encoding, extension, streamids, warnings)
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = mimeType
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedFileName.xls")
HttpContext.Current.Response.BinaryWrite(bytes)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
second way that based on this function :
Public Shared Sub ExportGridViewToExcelGridView(ByVal Filename As String, ByRef gvr As GridView, ByRef currentPage As Page)
Dim HtmlForm As System.Web.UI.HtmlControls.HtmlForm = New System.Web.UI.HtmlControls.HtmlForm()
currentPage.Controls.Add(HtmlForm)
HtmlForm.Controls.Add(gvr)
currentPage.Response.Clear()
currentPage.Response.Buffer = True
currentPage.Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename)
currentPage.Response.ContentType = "application/vnd.ms-excel"
currentPage.Response.ContentEncoding = System.Text.Encoding.UTF8
currentPage.Response.Charset = ""
currentPage.EnableViewState = False
Using strwriter As New StringWriter
Dim htmlwrt As HtmlTextWriter = New HtmlTextWriter(strwriter)
HtmlForm.RenderControl(htmlwrt)
htmlwrt.Flush()
currentPage.Response.Write(strwriter.ToString)
currentPage.Response.End()
End Using
End Sub
make sure that when you use second way to set the gridview paging property to false.

Mysql & Vb.net 'Invalid Attempt to Read when reader is closed'

I have run into this error while collecting data from a mysql database and placing it into a DataView control... This is my code:
Private Function PopulateActivity()
Dim loginStatement As String = "SELECT * FROM activity WHERE id = #userid"
Dim cmd As MySqlCommand = New MySqlCommand(loginStatement, mainconn)
cmd.Parameters.AddWithValue("#userid", LoggedInUser.ID)
Dim drMyAcount As MySqlDataReader = cmd.ExecuteReader()
Dim rowCount As Integer = 0
Dim rowAmount As Integer = 0
'gets count of rows returned from mysql query'
Using dt As New DataTable
dt.Load(drMyAcount)
rowAmount = dt.Rows.Count
End Using
'adds an entry for each item returned from the mysql query'
Do While rowCount < rowAmount
drMyAcount.Read() 'HERE IS WHERE ERROR OCCURS'
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1
Loop
drMyAcount.Close()
Return 0
End Function
I am unaware of why this is but it gives me an 'Invalid Attempt to Read when reader is closed' error one the:
drMyAccount.Read()
line...
I would appreciate any help on this topic! Thanks Much...
take out the dt.Load() , and counting of the rows prior to using datareader. DataReader has a built in property of .HasRows
if (drMyAcount.HasRows)
while (drMyAcount.Read())
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1 //you can still count rows in the loop
Loop
The MSDN documentation does not seem to specify, but apparently the DataTable.Load method closes the given IDataReader when it is done loading the data into the table. So, once you call dt.Load(drMyAcount), the drMyAcount will be closed.