display/retrieve image from sql database in vb.net - database

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()

Related

The connection was not closed the connection current state is open

Hye... I currently doing my final year project using vb.net and i got this error. Im tryin' to fix the error but still not succeed. I use ms access for database in my project. I try to put con.Open() before the 'dt' statement and con.Close() after the 'cboProduct.Select' but the result is the same. Really appreciate your helps. Thanks :)
'GLOBAL DECLARATIONS
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Acer User\Documents\MAKLUMAT IVENTORI.accdb"
Dim con As OleDbConnection = New OleDbConnection(conString)
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim ds As New DataSet
Private Sub RefreshData()
dt = New DataTable
ds = New DataSet
ds.Tables.Add(dt)
adapter = New OleDbDataAdapter("Select * FROM product WHERE lab_kod='66'", con)
adapter.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
labelID.Text = getAutoID()
lblLabCode.Text = "66"
cboProduct.Select()
Dim v_SQL As String = "SELECT * FROM kategori_product"
cmd = New OleDbCommand(v_SQL, con)
con.Open()
Dim v_dataReader As OleDbDataReader = cmd.ExecuteReader()
Dim v_dataTable As New DataTable
v_dataTable.Columns.Add("product_kod", Type.GetType("System.String"))
If v_dataReader.HasRows Then
While v_dataReader.Read
v_dataTable.Rows.Add(v_dataReader.GetString(0))
End While
cboProduct.DataSource = v_dataTable
End If
cboProduct.DisplayMember = "product_kod"
cboProduct.ValueMember = "product_kod"
v_dataReader.Close()
con.Close()
End Sub
Don't store short-lived objects, such as database connections, as global variables.
In fact, don't use global variables, ever, at all.
(though I note that assuming this is a Class and not a Module those are actually class fields, not globals, but you're still misusing them)
Your OleDbDataAdapter.Fill call requires the connection to be open, but you call .Fill(dt) before calling con.Open()
Use Using (using() in C#) blocks to ensure your database connection is always closed, even in the event of failure.

Dynamically creating a dropdown, with values from SQL server

I want to create a feature within my program that when i load in an excel file, it counts how many columns in the spreadsheet and dynamically creates a dropdown for each and every column, to select what header it should be, and bind it to the GridView .Data from SQL server will populate the dropdowns. Some problems i have run into is, how do i have a button where it asks for the file location? i have tried this way to load in a hardcoded location, but it doesnt work.
Sub SubmitBtn_Excel(Sender As Object, E As EventArgs)
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "C:\\spreadsheet.xlsx"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
GridView1.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
End Try
End Sub
I also have a method to call on the database with the table i have created to populate the data, should i put this method all in one method with the excel call?? considering that the dropdown id was dynamically created, it doesnt know how to find it because its not id'd in the HTML
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Page.IsPostBack Then
FillDeptDropdownList()
End If
End Sub
Protected Sub FillDeptDropdownList()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDbCon").ConnectionString)
Dim cmd As New SqlCommand("Select * from demofeepay.dbo.catagories", con)
Dim adp As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
adp.Fill(dt)
ddlDynamic.DataSource = dt
ddlDynamic.DataTextField = "catagory"
ddlDynamic.DataValueField = "ID"
ddlDynamic.DataBind()
ddlDynamic.Items.Insert(0, "Select Catagory")
End Sub
This is the method i have for creating the dropdown
Sub SubmitBtn_Excel(Sender As Object, E As EventArgs)
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "C:\\Users\\John\\Documents\\John\\EPP\\WorldNet_Notes\\CHRISTIAN_BROTHERS_HIGH_SCHOOL.xlsx"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
GridView1.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
End Try
End Sub
This is the HTML
<form id="form1" runat="server" style="overflow-x:hidden; width:100%">
<div>
<asp:button id="butOK" text="Add Dropdowns" onclick="SubmitBtn_Click" runat="server"/>
<asp:button id="BtnAddExcel" text="Add Spreadsheet" OnClick="SubmitBtn_Excel" runat="server"/>
</div>
<div id ="ddlDynamic">
<!-- Dynamic Dropdowns -->
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
I am aware that this is all over the place, as you can see im a bit lost. I dont really want anybody to spoon fed me the answer, im just unsure how to structure it, or could anybody point me in the right direction to find out more. New to vb. Thanks in advance :-)
First you will need to add a PlaceHolder control to your WebForm.
You will add your DropDownLists to this PlaceHolder this way:
foreach (var item in collection)
{
DropDownList ddl = new DropDownList();
lb.Items.AddRange(item.values);
ddl.ID = "ddl" + (PlaceHolder1.Controls.Count() + 1);
PlaceHolder1.Controls.Add(ddl);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
For your file button, you may want to use the FileUpload control.

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

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);

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.

Resources