VB.Net Open image from database to picturebox - database

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

Related

VB.Net connection

I'm slowly transitioning to VB.Net and it seems like the simplest of things are completely different. I'm trying to do a connection to SQL Server and just grab some data. I've tested the connection and it's fine. Now I'm trying to simply select some data from the server and display the first name in the Msgbox (or anything for that matter). Here is the code I've gotten so far....
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Public conn As New SqlConnection("data source=Tuys1;initial catalog=DDDBuyer; user ID=userID; password=password")
Private dA As New SqlDataAdapter("Select FirstName, LastName from tblBuyers where Buyerid=1473", conn)
Private dS As New DataSet
End Class
I'm not really sure how to go from here... I understand there is something like
.hasRows
if ds.hasrows then
msgbox = "HELLO"
End if
or something like displaying the FirstName in txtFirstName
I am trying to get an idea of how ths works and after some research it's hard to find a specific example that would help me do what I'm trying to accomplish.
Dim custAdapter As SqlDataAdapter = New SqlDataAdapter( _
"SELECT * FROM dbo.Customers", customerConnection)
Dim ordAdapter As OleDbDataAdapter = New OleDbDataAdapter( _
"SELECT * FROM Orders", orderConnection)
Dim customerOrders As DataSet = New DataSet()
custAdapter.Fill(customerOrders, "Customers")
ordAdapter.Fill(customerOrders, "Orders")
Dim relation As DataRelation = _
customerOrders.Relations.Add("CustOrders", _
customerOrders.Tables("Customers").Columns("CustomerID"), _
customerOrders.Tables("Orders").Columns("CustomerID"))
Dim pRow, cRow As DataRow
For Each pRow In customerOrders.Tables("Customers").Rows
Console.WriteLine(pRow("CustomerID").ToString())
For Each cRow In pRow.GetChildRows(relation)
Console.WriteLine(vbTab & cRow("OrderID").ToString())
Next
Next
As explained here

database connection with a chart

I have been trying to figure this out for a few days but every time I try and fix it I encounter the same error. I am trying to implement the data from my database into a candlestick style chart.Every time I run it i'm faced with this same error:
"An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: IErrorInfo.GetDescription failed with E_FAIL(0x80004005)."
I have used a combination of the limited resources given to me and code that I found here on a previously answered question to create the following code.
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim myConnection As OleDbConnection = New OleDbConnection
Dim provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile As String = "C:\Users\Ian\Documents\A2 Woking\Computing\Database1\Database_data_source .accdb"
Dim DatabasePass As String = "DatabasePW"
Dim connString As String = provider & dataFile
Dim execute As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myConnection.ConnectionString = connString
Dim objDataAdapter As OleDbCommand = New OleDbCommand("Select Time, Open, High, Low, Last FROM EUR_USD_TB", myConnection)
myConnection.Open()
execute = objDataAdapter.ExecuteReader
While execute.Read
chartTemplate.Series("dataSeries").Points.AddXY(execute("Time"), execute("Low"), execute("High"), execute("Open"), execute("Last"))
End While
' Close the reader and the connection
execute.Close()
myConnection.Close()
End Sub
End Class
Any help would be appreciated i'm sure its something annoyingly simple I don't get.
The path is correct---
The database is not protected by a password, that variable is for later---
The query works in access---
This same code works perfectly for accessing a separate table in my login

How to display database connection status in VB 2010

I'm developing Point of sales system. and i want to display database connection status for the users. Im using MS Access 2013 database and Visual Studio 2010 (VB). I created module for this project as follows,
Imports System.Data.OleDb
Module ModConVar
Public sql As String
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Public conn As OleDbConnection
Public connStr As String = System.Environment.CurrentDirectory.ToString & "\NCS_POS_DB.accdb"
Public Sub ConnDB()
Try
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & connStr & "")
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Module
And I have a label named lblDBStatus in main MDI form, I tried with followin code, but it dosent work.
If conn.State = ConnectionState.Open Then
lblDBStatus.Text = "CONECTED"
End If
any suggestions please ??
You're displaying "CONNECTED" only when the connection state is open. Otherwise your label will not show anything
Try this and make sure that the connection is open:
If conn.State = ConnectionState.Open Then
lblDBStatus.Text = "CONNECTED"
Else
lblDBStatus.Text = "DISCONNECTED"
End If
The OleDbConnection exposes a StateChanged event.
So you can track the state like this:
Public Sub ConnDB()
Using connection As New OleDbConnection("...")
AddHandler connection.StateChange, AddressOf Me.OnConnectionStateChange
Try
connection.Open()
'Do stuff..
Catch ex As Exception
Throw ex
Finally
RemoveHandler connection.StateChange, AddressOf Me.OnConnectionStateChange
End Try
End Using
End Sub
Private Sub OnConnectionStateChange(sender As Object, e As StateChangeEventArgs)
MessageBox.Show(e.CurrentState.ToString())
End Sub

how to save binary file to 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.

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