how to save binary file to database - database

Join Date: Dec 10
Posts: 10
caba11 is an unknown quantity at this point (<10)
how to save binary file to database
hi.
i need to save files into database...
i cant find why it is not working...
this is my code:
Public Sub importfiles(ByVal sFileName As String)
Dim cnSQL As SqlConnection
Dim cmSQL As SqlCommand
Dim strSQL
'Validate form values
'Read file into a stream
Dim fs As New FileStream(sFileName, FileMode.Open, FileAccess.Read)
Dim myData(fs.Length) As Byte
fs.Read(myData, 0, fs.Length)
fs.Close()
Try
'Build SQL
strSQL = "insert into data_cesta(ID, cesta) values (#ID, #cesta)"
cnSQL = New SqlConnection("Data Source=.;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True")
cmSQL = New SqlCommand(strSQL, cnSQL)
cmSQL.Parameters.Add(New SqlParameter("#ID", SqlDbType.Int)).Value = ID
cmSQL.Parameters.Add(New SqlParameter("#cesta", SqlDbType.NText)).Value = myData
' cmd2.Parameters.Add("#ID", SqlDbType.Int).Value = ID
' cmd2.Parameters.Add("#cesta", SqlDbType.NText).Value = myData
'Open connection and execute the command
cnSQL.Open()
cmSQL.ExecuteNonQuery()
'Close and clean up objects
cnSQL.Close()
cmSQL.Dispose()
cnSQL.Dispose()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
without try it says "cmSQL.ExecuteNonQuery()"-"Failed to convert parameter value from a DataGridViewTextBoxColumn to a Int32."

It looks as though you are loading some file paths into a DataGrid before having them processed into your database.
By default, your ID field is being passed to the procedure as the DataGridViewTextBoxColumn object within the DataGrid. You need to retrieve the text within that object.
You can do so by accessing the associated DataGridViewTextBoxCell object on the row being processed. Within the DataGridViewTextBoxCell object is a property called "Value" which will have the ID value you need.
Without seeing more code, it's hard to give you the exact code, but check out the DataGridViewCell object for some helpful code, since the TextBoxCell inherits from this class.

Related

VB.Net Open image from database to picturebox

I'm trying to open an image from my database to a picture box but I just don't how to do it.
I've searched for some answers and I am not familiar with the codes for I am beginner only.
The only codes that I researched about are for connecting the database to the system:
Imports System.Data.OleDb
Module Module1
Public acsconn As New OleDbConnection
Public acsdr As OleDbDataReader
Public acsda As New OleDbDataAdapter
Public acscmd As New OleDbCommand
Public strsql As String
Public acsds As New DataSet
Public Sub connect()
Try
acsconn.ConnectionString = "provider=microsoft.jet.oledb.4.0; data source=|datadirectory|\database1.mdb;"
acsconn.Open()
If acsconn.State = ConnectionState.Open Then
MsgBox("Connected")
Else
MsgBox("Error")
End If
Catch ex As Exception
End Try
End Sub
End Module
I do not know what is next. BTW, those codes - I used it for saving the image to the database.
I think this is the sort of thing you are looking for:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub

delete record from database in listview in vb

I have a problem. In the properties of listview which is checkboxes = "True". Using this checkbox, I want to delete the data in listview and in the database.
Below is the code:
If MessageBox.Show("Do you really want to DELETE this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation cancel", MsgBoxStyle.Information, "Information")
End If
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
Using con = New SqlConnection(dbSource)
Using cmd = New SqlCommand(sql, con)
con.Open()
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
cmd.Parameters.AddWithValue("#code", ColumnRoomCode.Text)
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
Using above code, only the data in listview is deleted. The data in the database not deleted.
The interface for listviewitem:
Thank you if you all can help me. :)
A Command should be executed to have any effect on the database. You need to add this
cmd.ExecuteNonQuery()
in every loop.
Also the connection could be opened just before entering the loop and should be closed afterward. (Using Statement is recommended here)
Said that, please take a look on Parameterized queries because your code is open to Sql Injections and parsing problems. Also the sql command to delete a record doesn't need a list of fields after the FROM table part.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
' Parameterized query
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
' Using statement to ensure proper closing and disposing
' of the objects SqlConnection and SqlCommand
using con = New SqlConnection(dbSource)
using cmd = New SqlCommand(sql, con)
con.Open()
' Add a parameter just one time before the loop with an empty string
cmd.Parameters.AddWithValue("#code", "")
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
' Set the parameter value with the value extracted from the ListViewItem
Dim RoomCode = lvItem.Text
cmd.Parameters("#code").Value = RoomCode
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
End Sub
One last note. The ColumnRoomCode textbox (?) is always the same, so calling delete one time is enough, but I suppose that this should be changed with some value extrated by you current ListViewItem

VB.NET Reference new form object's listview from another class

On a form i have a listview with a contextmenu.
Right click on a listview item shows the context menu.
When i click on the menubutton, what i would like to happen is the following :
A form i called TaskLog will appear, it contains only a listview
(This is the code i have) :
Private Sub ShowLogToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowLogToolStripMenuItem.Click
logform = New TaskLog()
logform.task = "taskname"
logform.server = "servername"
logform.Show()
End Sub
That listview should be filled with data from a database before it shows, therefore i have the following in the load event of the TaskLog Form
Public Class TaskLog
Private db As Database = New Database
Public task As String
Public server As String
Private Sub TaskLog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
db.connect()
db.getTaskLog(task, server, Me)
End Sub
End Class
Then in the database class gettask function i call the database, store data in an object, which all works fine. Only problem here is that my database object cannot find the listview and the form, even if i pass the form as a variable to this function (frm as TaskLog).
Public Function getTaskLog(taskname As String, server As String, frm As TaskLog) As Boolean
'Declare sql command variable
Dim command As New SqlCommand
'Try to open db connection
Try
connection.Open()
command.Connection = connection
'Set query to command object text
command.CommandText = "select * from tasklog where ltrim(rtrim(server)) Like'" & Trim(server) & "%' and ltrim(rtrim(task)) = '" & Trim(taskname) & "'"
'Declare data reading pbject
Dim rdr As SqlDataReader = command.ExecuteReader()
'Perform operations while rows are returned from database
While rdr.Read()
'Store database entry to TaskData Object
taskLogData = New TaskData(rdr("frequency").ToString, rdr("start"), rdr("duration"), rdr("delay"), rdr("rescheduled"), rdr("forced"), rdr("task"), rdr("server"), rdr("email"), rdr("message"), rdr("status"), rdr("logtime"))
Dim new_item As New _
ListViewItem(Trim(taskLogData.task_server.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_name.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_status.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_frequency.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_nextrun.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_forced.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_rescheduled.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_rescheduled.ToString))
new_item.Group = frm.ListView1.Groups(Trim(taskData.task_status.ToString))
frm.ListView1.Items.Add(new_item)
End While
Return True
Catch ex As Exception 'If connection fails return error message
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Return True
Finally 'After connection close database
connection.Close()
End Try
End Function
Object Reference not set to an instance of an object appears on the following line in the function above:
frm.ListView1.Items.Add(new_item)
Can someone see the problem, and hopefully some help ? I tried a couple of things but still not sure about what to do best here. Thanks !!!!!!!
This line
new_item.Group = frm.ListView1.Groups(Trim(taskData.task_status.ToString))
refers to a Group that should exist in the ListView1. You could comment it out if it is not needed

Loading data from SQL Server row by row to textboxes

I am trying to retrieve data row by row from my SQL Server and load them into my respective textboxes, I was doing the below code but of course it doesn't work as the For Each loop will load every single textboxes with each data retrieved, ran out of ideas. Appreciate if someone can give me a boost here. Thanks.
Private Sub retrieve_Data()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=HPEnvy-HP; Initial Catalog=Cinema; User Id=<id>; Password=<password>;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT [movie_ID], [movie_Title] FROM [Movie_Table] ORDER BY [MOVIE_ID] "
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim reader As String = lrd(1).ToString
Dim arrLoad As New ArrayList
arrLoad.Add(lrd(1).ToString)
For i = 0 To arrLoad.Count - 1
For Each cCtrl As Control In Panel1.Controls
If TypeOf cCtrl Is TextBox Then
Dim txtBox As New TextBox
txtBox = cCtrl
txtBox.Text = arrLoad.Item(i)
End If
Next
Next
End While
Catch ex As Exception
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
End Sub
you just "new" your textbox,
you didn't add your textbox to your form.
you should add some code like that:
this.Controls.Add(textbox);
or
this.Panel1.Controls.Add(textbox);

display/retrieve image from sql database in vb.net

This should be pretty simple for a pro. I have images in sql server database and I want to retrieve them in my aspx (vb.net) file.
I have in aspx this image control -
in vb.net i have started this code -
Private Sub ImageDisplay()
Dim SqlCnn As SqlConnection = Nothing, sql As String = ""
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
Dim newImage As Image = Nothing
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
newImage = Image.FromStream(ms, True)
End Using
image1.Image = newImage
End If
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub
I am getting error on 2 places.
- newImage = Image.FromStream(ms, True)
- image1.Image = newImage
Fromstream is not a member of system.web.ui.webcontrols.image
and second error Image is not a member of system.web.ui.webcontrols.image
You need both a command object and a data reader. However, you are putting them in the wrong page.
If you check out the properties of the Image control you will see that it doesn't have any Image property, so you can't load an image and put in the control. The reason for that is that you can't send both the page and the image in the same response, instead the browser has to request the image separately when the page loads.
To get the image from the database and show in the web page you need a separate proxy page that you can use to get only the image data from the database. In the ImageUrl property of the Image control you would put something like "GetImage.ashx". Then you make an HTTP handler with that name that will just get the image data from the database and write to the response stream.
Example:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub
Dim cn As SqlConnection
cn = New SqlConnection
cn.ConnectionString = "Data Source=UMAR\UMAR;Initial Catalog=DMCHS;Integrated Security=True"
Dim cmd As New System.Data.SqlClient.SqlCommand("select D1 from DBFile where mem_no=2")
cmd.Connection = cn
cmd.CommandType = CommandType.Text
Dim ImgStream As New IO.MemoryStream(CType(cmd.ExecuteScalar, Byte()))
PictureBox1.Image = Image.FromStream(ImgStream)
ImgStream.Dispose()
cmd.Connection.Close()

Resources