Data adds up but does not display in single compile - sql-server-2008

I am using service-based database (.mdf file) to add name and the photo to my database in VS 2010. After debugging and adding the data it adds up into the .mdf but while trying to retrieve it, it doesn't show. It shows only after next debugging. I am really stuck in this for 2 days please help me.
Thank you in advance.
Connection string I am currently using :
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & path & "Database1.mdf;Integrated Security=True;User Instance=True")
This is the code I am using to save the image and name :
Dim cmd As New SqlCommand("INSERT INTO Information VALUES(#name,#photo)", con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
And this is the code I am using to display data in the datagridview
Me.InformationTableAdapter.Fill(Me.Database1DataSet.Information

Related

how to save a byte() to my SQLDatabase using VB.net

I know that there are already a couple of questions which seems like my problem but I tried to copy a lot of it and tried but can’t get the resold I want.
Actually is my target to save an image from a Picture Box as Byte() into mySQL Database.
At first I tried the simple way like
Dim acCust As Image = pgbox.image
Dim picBytes() As Byte
Using ms As New MemoryStream
cust.Save(ms, cust.RawFormat)
picBytes = ms.ToArray()
End Using
but with this I run into a general GUI error so I copied the Picture at first like this
Dim rec As New Rectangle(0, 0, acCust.Width, acCust.Height)
Dim mus As New ImageFormatConverter
Dim muster As New Bitmap(rec.Width, rec.Height)
Dim cust As Image
Using grp = Graphics.FromImage(muster)
grp.DrawImage(acCust, New Rectangle(0, 0, rec.Width, rec.Height), rec, GraphicsUnit.Pixel)
cust = muster
End Using
If I use after that again the code
Dim picBytes() As Byte
Using ms As New MemoryStream
cust.Save(ms, cust.RawFormat)
picBytes = ms.ToArray()
End Using
sqlconection.Open()
Dim query As String = "INSERT INTO tblimg(img) VALUES ('#image');"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("image", picBytes)
com.ExecuteNonQuery()
sqlconection.Close()
everything looks sofa ok but if I read it like this
Dim imgData As Byte()
Dim sql As String = "SELECT img FROM tblimg"
sqlconection.Open()
Dim cmd As New MySqlCommand(sql, sqlconection)
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
imgData = TryCast(rdr.Item("img"), Byte())
' in case this record has no image
If imgData IsNot Nothing Then
' ToDo: dispose of any previous Image
' create memstream from bytes
Using ms As New MemoryStream(imgData)
' create image from stream, assign to PicBox
pbbox.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
I got an alarm message
Eine nicht behandelte Ausnahme des Typs "System.ArgumentException" ist in System.Drawing.dll aufgetreten.
Zusätzliche Informationen: Ungültiger Parameter.
(Sorry it's in German)
Has anybody an idea what and were it’s going wrong?
If I use the the picByts () in a new memory stream and convert it back to an image then I got the correct result. It seems like there is a problem with the up or download query
in my Server I use the variable type LongBlob
You save a Byte array to a database in exactly the same way as you save any other data. You write your SQL, you add a parameter to a command and you set its value. This:
Dim query As String = "INSERT INTO tblimg(img) VALUES ('#image');"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("image", picBytes)
is wrong. You only wrap literal strings in single quotes in SQL code. That should be like this:
Dim query As String = "INSERT INTO tblimg(img) VALUES (#image);"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("#image", picBytes)
No single quotes around the parameter in the SQL and use the actual parameter name when adding it to the command. I'd also recommend using Add rather than AddWithValue but that's a discussion for another time.

Display saved PDF file from database to PDFVIEWER

I have successfully saved a pdf file to my database (MySQL) as a longblob and used this code :
opf.Filter = "PDF FILES |*.pdf"
If opf.ShowDialog = Windows.Forms.DialogResult.OK Then
//Display the PDF you want to save in the PDFVIEWER
pdfview.src = opf.FileName
Dim Mystream As New FileStream(opf.FileName, FileMode.Open)
Dim filesize As Long = Mystream.Length
Dim buffer(filesize) As Byte
Mystream.Read(buffer, 0, filesize)
//Save the pdf file to the database
Dim query As String = "insert into sample(pdfnaho)values(#file)"
Dim cmd As New MySqlCommand(query, con)
con.Open()
cmd.Parameters.AddWithValue("#file", buffer)
cmd.ExecuteNonQuery()
MsgBox("SAVED!")
con.Close()
End If
Then I used this code for displaying but It doesn't work and I don't know what to do :
Dim query As String = "select * from sample where id = 1"
Dim cmd As New MySqlCommand(query, con)
con.Open()
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
If dr.HasRows Then
pdfview.src = dr.GetString("pdfnaho")
End If
End While
con.Close()
How should I display my saved pdf file from database? Thank You
I can not put this as a comment because I don't have enough reputation.
What PDF viewer are you using?. If it is the Adobe PDF Viewer I am almost sure (from previous research for another project) that you can not stream into it.
This is an example from my previous project, I modified it to fit yours, make sure to edit the query to fit your table and columns names.
You have to ran a query that return only the cell with the file in binary.
Dim query as String = "SELECT file_content FROM sample WHERE ID=1;"
Public Sub OpenPDF()
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
pdfview.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New MySqlCommand(query, con)
Dim Buffer As Byte()
con.open()
Buffer = cmd.ExecuteScalar
con.close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
pdfview.src = Application.StartupPath() & "\temp.file"
End Sub
With this example, the code will check if there is an existing "temp.file" and delete it, then load nothing on the pdfviewer to clear whatever is displaying.
The the database connection, get the data, store it on a file then display it with the pdfviewer.

Access is not a valid path

The code below is when a staff takes customers orders via the system and the system states "order sent".
The VB.NET works perfectly, it's just that the data from VB should automatically go to my Access Database. The problem below are codes lines 11/12 where I enter my database file and which will hold the data from VB.Net. It gives me
"C:\user\public\stu-storage1\user-area\4\oo423\My
Documents\Database511.accdb(Access 2007 - 2013 file format) -Access'
is not a valid path. Make sure that the path name is spelled
correctly and that you are connected to the server on which the file
resides".
MessageBox.Show("Order sent")
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\user\public\\stu-storage1\user-area\4\oo423\My Documents\Database511.accdb(Access 2007 - 2013 file format) -Access"
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConnection = New OleDbConnection
MyConnection.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Database511", MyConnection)
da.Fill(ds, "Database511.accdb")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
The error message is perfectly clear. So change this line to:
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\users\public\stu-storage1\user-area\4\oo423\My Documents\Database511.accdb"

Crystal Report 13 prompts Database Login in VS 2010

I am currently having problem displaying the Crystal Report in my VB.Net(VS2010) application. I Googled this issue, found similar problem, but their solution didn't fixed mine.
Everytime I call the CR report from my VB application, it always prompts for a Database Login. I've entered my DB credentials but it fails. I am connecting to a MySQL5.1 via ODBC connector.
In my Crystal Report, I have created a custom Command which accept 2 parameters from my application, e.i, dateFrom and dateTo, which I used to query between the date range.
I've noticed that when I took off my code where it sets the Crystal Report parameter value, the Database Login doesn't appear.
Here's my code snippet:
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim cryRpt As New ReportDocument
Dim CRTable As CrystalDecisions.CrystalReports.Engine.Table
Dim CRTLI As CrystalDecisions.Shared.TableLogOnInfo
cryRpt.Load(appPath & "\Reports\crDtrLogs.rpt")
frmReportViewer.crReportViewer.Refresh()
For Each CRTable In cryRpt.Database.Tables
CRTLI = CRTable.LogOnInfo
With CRTLI.ConnectionInfo
.ServerName = "dtrsql"
.UserID = "root"
.Password = "root"
.DatabaseName = "dtrsql"
End With
CRTable.ApplyLogOnInfo(CRTLI)
Next CRTable
When I took this out, everything works fine even without adding the table connection info
cryRpt.SetParameterValue("dtpFrom", dtpFrom.Value.Date.ToString("yyyy-MM-dd"))
cryRpt.SetParameterValue("dtpTo", dtpTo.Value.Date.ToString("yyyy-MM-dd"))
cryRpt.SetParameterValue("strDateRange", dtpFrom.Value.Date.ToString("MMMM dd, yyyy") & " - " & dtpTo.Value.Date.ToString("MMMM dd, yyyy"))
frmReportViewer.crReportViewer.ReportSource = cryRpt
frmReportViewer.Show()
As always, any help is greatly appreciated.
eassy and simple solution for all ....
open field explorer---> database field --->Right Click -->current Data source --->reports connection----->report ----->property ----> set Property as---
Data Source: .\Databasename.accdb
and code on viewer form load as
Dim cryRpt As New ReportDocument
Dim Report1 As New rptItemWise
Dim strServerName As String
strServerName = Application.StartupPath
rptItemWise.SetDatabaseLogon("admin", "", strServerName, "dastabasename.accdb", True)
cryRpt.Load(Application.StartupPath + "\rptItemWise.rpt")
also change the report connection same as data source i think that code work for you ..
Check this code. I guess you should access to the database like this:
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
cryRpt.Load(appPath & "\Reports\crDtrLogs.rpt")
crConnectionInfo.ServerName = "YOUR SERVER NAME"
crConnectionInfo.DatabaseName = "YOUR DATABASE NAME"
crConnectionInfo.UserID = "YOUR DATABASE USERNAME"
crConnectionInfo.Password = "YOUR DATABASE PASSWORD"
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next CrTable

Need help filling datagrid from MySQL

I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try
You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).