I'm using VB.NET and SQL Server for my system. I have a problem saving an image into the database. I need to save and retrieve image on the same page but I get an error:
unable to cast System.DBNull to system bytes.
I have tried several coding to fix my coding but it does not worked.
Code for retrieve image.
Dim id As String = txtImages.Text.Trim() 'txtImages is textbox name
Image1.Visible = id <> ""
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id
='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the
serch textbox
If dt.Rows.Count > 0 Then
Dim bytes As Byte() = TryCast(dt.Rows(0)("ImagePic"), Byte())
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image
in db the message will displayed
End If
End If
End Sub
Code for save image
Dim fileName As String = String.Empty
Dim filePath As String = String.Empty
Dim getPath As String = String.Empty
Dim pathToStore As String = String.Empty
Dim bytes As [Byte]()
Dim fs As FileStreamenter code here
Dim br As BinaryReader
Dim cmd As New SqlCommand("Updateonlyimage_Sp3", cs) ' SQL command for this page is inside SQL Server I declare it as Insertapprovalcustom_Sp2"
cmd.CommandType = CommandType.StoredProcedure
Try
If FileUpload1.HasFile Then
fileName = FileUpload1.FileName
filePath = Server.MapPath("HSCODE/" & Convert.ToString(System.Guid.NewGuid()) & fileName)
'path to doucument inside approval_pdf file
FileUpload1.SaveAs(filePath)
cmd.Parameters.AddWithValue("#id", Request.QueryString("id"))
cmd.Parameters.AddWithValue("#ImagePicName", fileName)
Dim getPos As Integer = filePath.LastIndexOf("\")
Dim len As Integer = filePath.Length()
getPath = filePath.Substring(getPos, len - getPos)
pathToStore = getPath.Remove(0, 1)
cmd.Parameters.AddWithValue("#ImagePicPath", pathToStore)
fs = New FileStream(filePath, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
bytes = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
cmd.Parameters.AddWithValue("#ImagePic", bytes)
cmd.Parameters.AddWithValue("#ContentType", FileUpload1.PostedFile.ContentType)
Related
enter image description hereI am using a SQL Server Compact 3.5 database file (.sdf) in vb.net
There was an error parsing the query. [Token line number,Token line offset,,Token in error,,]
Dim flag As Boolean
Dim flag2 As Boolean
Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|"
Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
flag2 = (Me.OpenFileDialog1.ShowDialog() = DialogResult.OK)
If flag2 Then
flag = (Operators.CompareString(FileSystem.Dir(Me.OpenFileDialog1.FileName, FileAttribute.Normal), "", False) <> 0)
End If
Dim myConnectionStringMDB As String = "provider=Microsoft.Ace.OLEDB.12.0;" & "data source=" & Me.OpenFileDialog1.FileName
Dim myConnectionStringSQL As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" & "Data Source=" & Application.StartupPath & "\Archive.sdf"
Using conSQL As OleDbConnection = New OleDbConnection(), conMDB As OleDbConnection = New OleDbConnection()
conSQL.ConnectionString = myConnectionStringSQL
conSQL.Open()
conMDB.ConnectionString = myConnectionStringMDB
conMDB.Open()
Using cmdSQL As OleDbCommand = New OleDbCommand(), cmdMDB As OleDbCommand = New OleDbCommand()
cmdMDB.CommandType = Data.CommandType.Text
cmdMDB.Connection = conMDB
cmdMDB.CommandText = "SELECT * FROM [student]"
Dim daMDB = New System.Data.OleDb.OleDbDataAdapter(cmdMDB)
Dim dt = New Data.DataTable()
daMDB.Fill(dt)
For Each dr As Data.DataRow In dt.Rows
' change row status from "Unchanged" to "Added" so .Update below will insert them
dr.SetAdded()
Next
cmdSQL.CommandType = Data.CommandType.Text
cmdSQL.Connection = conSQL
cmdSQL.CommandText = "SELECT * FROM [student]"
Dim daSQL = New System.Data.OleDb.OleDbDataAdapter(cmdSQL)
Dim cbuilderMDB = New OleDbCommandBuilder(daSQL)
cbuilderMDB.QuotePrefix = "["
cbuilderMDB.QuoteSuffix = "]"
daSQL.Update(dt)
End Using
conSQL.Close()
conMDB.Close()
End Using
I got rid of the extra boolean variables flag and flag2 and just tested the values directly.
I divided the Using blocks into 2 blocks so the first group of objects can be closed and disposed before the next group starts their work.
I shortened the code by passing properties directly to the constructors of the objects where possible. DataAdapter and StringBuilder also expose a .Dispose method so I included them in the Using blocks.
daMDB.AcceptChangesDuringFill = False
This line of code allows the .DataRowState to remain as Added (normally it is changed to Unchanged by the .Fill method) so, the DataTable will be ready to add all the records to the second table without the loop.
I don't believe that student is a reserved word in either database so I removed the square brackets.
Both the .Fill and the .Update methods of the DataAdapter will .Open and .Close the connection if they find the connection closed. If they find it open they will leave it open. So, closing the connection is not necessary. Also the End Using closes and disposes all objects included in the Using portion (first line including commas) of the block.
Private Sub OPCode()
OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
Dim MDBFile As String
If OpenFileDialog1.ShowDialog = DialogResult.OK AndAlso Not String.IsNullOrEmpty(OpenFileDialog1.FileName) Then
MDBFile = OpenFileDialog1.FileName
Else
Exit Sub
End If
Dim myConnectionStringMDB As String = "provider=Microsoft.Ace.OLEDB.12.0;" & "data source=" & MDBFile
Dim myConnectionStringSQL As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" & "Data Source=" & Application.StartupPath & "\Archive.sdf"
Dim dt = New Data.DataTable()
Using conMDB As OleDbConnection = New OleDbConnection(myConnectionStringMDB),
cmdMDB As OleDbCommand = New OleDbCommand("SELECT * FROM student", conMDB),
daMDB As New System.Data.OleDb.OleDbDataAdapter(cmdMDB)
daMDB.AcceptChangesDuringFill = False
daMDB.Fill(dt)
End Using
Using conSQL As OleDbConnection = New OleDbConnection(myConnectionStringSQL),
cmdSQL As OleDbCommand = New OleDbCommand("SELECT * FROM student", conSQL),
daSql As New OleDbDataAdapter(cmdSQL),
cbuilderMDB As New OleDbCommandBuilder(daSql)
daSql.Update(dt)
End Using
End Sub
I am trying to retrieve the image from the database for a particular user after logging into the program. The problem I encountered is "Parameter is not valid."
The code:
Dim ArrImage() As Byte
Dim cn As New SqlConnection("server=.\sqlexpress;Initial Catalog=hazimdb;Integrated Security=True")
Dim Ms As New IO.MemoryStream
Dim da As New SqlDataAdapter("SELECT * FROM userlog WHERE username= '" & Label10.Text.Trim & "'", cn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count <> 0 Then
Label10.Text = dt.Rows(0).Item("username")
If Not IsDBNull(dt.Rows(0).Item("pictu")) Then
ArrImage = dt.Rows(0).Item("pictu")
For Each arr As Byte In ArrImage
Ms.WriteByte(arr)
Next
PictureBox8.Image = System.Drawing.Image.FromStream(Ms)
End If
Else
MsgBox("No Match Found")
End If
Set the memory stream position to 0 before trying to get an image out of it.
Ms.Flush()
Ms.Position = 0
My output appends the current column in datagridview whereas i wanted to view the output from excel file to the datagridview in series.What shall i do?
Can i get the solution for the same as i cant import excel file in new datagridview the requirement is to import all excel cells to corresponding in the current datagridview.
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim excel As String
Dim OpenFileDialog As New OpenFileDialog
Dim conn As OleDbConnection
Dim dta As OleDbDataAdapter
DataGridView2.Rows.Clear()
Dim dts As DataSet
OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
OpenFileDialog.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"
If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
Dim fi As New FileInfo(OpenFileDialog.FileName)
Dim FileName As String = OpenFileDialog.FileName
excel = fi.FullName
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;")
dta = New OleDbDataAdapter("Select * From [Sheet1$]", conn)
dts = New DataSet
dta.Fill(dts, "[Sheet1$]")
DataGridView2.DataSource = dts
DataGridView2.DataMember = "[Sheet1$]"
conn.Close()
With DataGridView2
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Enrollment No"
.Columns(1).HeaderCell.Value = "Name"
.Columns(2).HeaderCell.Value = "Sub Name"
.Columns(3).HeaderCell.Value = "Examination"
.Columns(4).HeaderCell.Value = "Semester"
.Columns(5).HeaderCell.Value = "Out of"
.Columns(6).HeaderCell.Value = "Marks Obtained"
.Columns(7).HeaderCell.Value = "Grade"
End With
DataGridView2.Columns.Item(0).Width = 100
DataGridView2.Columns.Item(1).Width = 120
DataGridView2.Columns.Item(2).Width = 100
DataGridView2.Columns.Item(3).Width = 70
DataGridView2.Columns.Item(4).Width = 90
DataGridView2.Columns.Item(5).Width = 50
DataGridView2.Columns.Item(6).Width = 70
DataGridView2.Columns.Item(7).Width = 70
DataGridView2.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
With DataGridView2
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Enrollment No"
.Columns(1).HeaderCell.Value = "Name"
.Columns(2).HeaderCell.Value = "Sub Name"
.Columns(3).HeaderCell.Value = "Examination"
.Columns(4).HeaderCell.Value = "Semester"
.Columns(5).HeaderCell.Value = "Out of"
.Columns(6).HeaderCell.Value = "Marks Obtained"
.Columns(7).HeaderCell.Value = "Grade"
End With
DataGridView2.Columns.Item(0).Width = 100
DataGridView2.Columns.Item(1).Width = 120
DataGridView2.Columns.Item(2).Width = 100
DataGridView2.Columns.Item(3).Width = 70
DataGridView2.Columns.Item(4).Width = 90
DataGridView2.Columns.Item(5).Width = 50
DataGridView2.Columns.Item(6).Width = 70
DataGridView2.Columns.Item(7).Width = 70
DataGridView2.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
With Me.DataGridView2
.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke
.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender
End With
MsgBox("Importing Data has been Cancelled")
End If
End Sub
Since the excel file appears to be what you want to display in the datagrid I think that you should be able to do like the below. Make the Datatable the datasource for your datagrid. IE your datagridview is bound to your datatable.
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim excel As String
Dim OpenFileDialog As New OpenFileDialog
Dim conn As OleDbConnection
Dim dta As OleDbDataAdapter
DataGridView2.Rows.Clear()
Dim dt As New DataTable
OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
OpenFileDialog.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"
If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
Dim fi As New FileInfo(OpenFileDialog.FileName)
Dim FileName As String = OpenFileDialog.FileName
excel = fi.FullName
dim conn as New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;")
dim dta as new New OleDbDataAdapter("Select * From [Sheet1$]", con
da.Fill(dt)
DataGridView2.Datasource = dt
End Sub
In a table image column is storing as 0xFF...how to display this format file in picture box in vb.net winforms? I tried below code but not working and showing readtimeout/writetimeout error ..help me..advanced thanks..
Private Sub DisplayNameAttribute_UserImage()
Try
strimage = "SELECT userimage from MKBLOGIN where empcode='" & str_empcode & "'"
imagedatabytes = objcommonvalidation.func_loadUserImage(strimage)
mem = New MemoryStream(imagedatabytes)
PictureBox1.Image = ToImage(imagedatabytes)
Catch ex As Exception
End Try
End Sub
Public Function func_loadEmpImage(ByVal str_query As String) As Byte()
Try
Dim ds As New DataSet
da = New SqlDataAdapter(str_query, con)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
data = New Byte(0) {}
data = ds.Tables(0).Rows(0)("userimage")
End If
Return data.ToArray()
Catch ex As Exception
Return data.ToArray()
End Try
End Function
Public Shared Function ToImage(Data As Byte()) As Image
If Data Is Nothing Then
Return Nothing
End If
Dim img As Image
Using stream As New MemoryStream(Data)
Using temp As Image = Image.FromStream(stream)
img = New Bitmap(temp)
End Using
End Using
Return img
End Function
cmd = New SqlCommand("Select userimage from table", con)
dr = cmd.ExecuteReader
dr.read
Dim ImgStream As New IO.MemoryStream(CType(sqldr("userimage"), Byte()))
PictureBox1.Image = Image.FromStream(ImgStream)
ImgStream.Dispose()
Dim stream As New IO.MemoryStream
Dim img() As Byte
img = table.Rows(0)(1)
Dim ms As New MemoryStream(img)
pddraw.Image = Image.FromStream(ms)
conn.Open()
command.ExecuteNonQuery()
conn.Close()
this is only for display not for editing
I need to export a lot (nearly a million) of data everyday from SQLServer to Excel. The data is being processed through a stored procedure then I put them on the DataSet and tried to export using this code:
`
Private Sub ExportToExcel(ByVal dtTemp As System.Data.DataTable, ByVal filepath As String)
Dim strFileName As String = filepath
Dim _excel As New Excel.Application
Dim wBook As Excel.Workbook
Dim wSheet As Excel.Worksheet
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dtTemp
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
wSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
wSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
wBook.SaveAs(strFileName)
ReleaseObject(wSheet)
wBook.Close(False)
ReleaseObject(wBook)
_excel.Quit()
ReleaseObject(_excel)
GC.Collect()
End Sub`
Is there any faster way for this?
How about DataSet to Clipboard then paste it to excel?
One way is to save the DataSet as an XML file:
myDataSet.WriteXml("c:\file.xml")
There is a much faster way involving SQL Data Pump (Import Export DTS). You can save a DTS Package (that exports data from SQL to Excel about 1000 rows per second) then run that package using SQL Server Agent. This way, you don't have to iterate to all the rows and columns one by one and you don't need to have a VB code.
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Linq
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Core
Imports Microsoft.VisualBasic.DateAndTime
Private Sub Btn_Add_Click(sender As Object, e As EventArgs) Handles btn_Add.Click
DataSetToExcel(ReturnDS("Select * from Membership"), "Test")
End Sub
Public Shared Function DataSetToExcel(myDS As DataSet, fileName As String)
Try
Dim Excel As Object = CreateObject("Excel.Application")
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
Dim i As Integer = 1
For col = 0 To myDS.Tables(0).Columns.Count - 1
.Cells(1, i).value = myDS.Tables(0).Columns(col).ColumnName
.Cells(1, i).EntireRow.Font.Bold = True
i += 1
Next
i = 2
Dim j As Integer = 1
For col = 0 To myDS.Tables(0).Columns.Count - 1
i = 2
For row = 0 To myDS.Tables(0).Rows.Count - 1
.Cells(i, j).Value = myDS.Tables(0).Rows(row).ItemArray(col)
i += 1
Next
j += 1
Next
Dim MyTime As String
MyTime = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")
.Application.DisplayAlerts = False
.ActiveCell.Worksheet.SaveAs(fileName & "_" & MyTime & ".xlsx")
.Workbooks.Close()
End With
Catch ex As Exception
End Try
Return ""
End Function
Public Shared Function ReturnDS(Query As String) As DataSet
Dim con = New SqlConnection(Crypto.ConString)
Dim cmd As New SqlCommand()
Dim myDA As New SqlDataAdapter()
Dim myDS As New DataSet 'The DataSet you created.
cmd.Connection = con
cmd.CommandText = Query
cmd.CommandType = CommandType.Text
myDA.SelectCommand = cmd
myDA.Fill(myDS)
Return myDS
End Function