Import and Export csv File from DataGridView - vb.net

High there, I'm currently making a small piece of software for a college project, The goal of the project is for the user to import ingredients and infomration and then they can create meals with these ingredients.
I'm having an issue though where when I load my csv file in after I've used the software once to add in a new ingredient I get the error: "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" and it highlights the section of the code "newRow("Protien") = columns(1)" Now I think is because when it loads in the data from the recently saved csv file it has a row at the top that is filled with the headers, is there any way that I can save the csv file without including the headers from the data table?
Code that laods in the csv file:
'Sets up the data table that will be used to store the ingredients and their information.'
With ingredientTable
.Columns.Add("Name", System.Type.GetType("System.String"))
.Columns.Add("Protien", System.Type.GetType("System.Decimal"))
.Columns.Add("Fat", System.Type.GetType("System.Decimal"))
.Columns.Add("Salt", System.Type.GetType("System.Decimal"))
.Columns.Add("Carbs", System.Type.GetType("System.Decimal"))
.Columns.Add("Calories", System.Type.GetType("System.Decimal"))
End With
'Loads in the information from the CSV file to display all the previouly saved ingredients'
Dim fileReader As New IO.StreamReader("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", System.Text.Encoding.Default)
Dim ingredientString As String = ""
Do
ingredientString = fileReader.ReadLine
If ingredientString Is Nothing Then Exit Do
'Reads what is on the CSV file and sets up the columns and the rows.'
Dim columns() As String = ingredientString.Split(",")
Dim newRow As DataRow = ingredientTable.NewRow
newRow("Name") = columns(0)
newRow("Protien") = columns(1)
newRow("Fat") = columns(2)
newRow("Salt") = columns(3)
newRow("Carbs") = columns(4)
newRow("Calories") = columns(5)
ingredientTable.Rows.Add(newRow)
Loop
fileReader.Close()
DataGridView1.DataSource = ingredientTable
Me.Text = ingredientTable.Rows.Count & "rows"
Code that saves the CSV file:
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
#Region "Save ingredients"
Dim csvFile As String = String.Empty
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
'Used to ge the rows
For Each row As DataGridViewRow In DataGridView1.Rows
'Used to get each cell in the row
For Each cell As DataGridViewCell In row.Cells
csvFile = csvFile & cell.FormattedValue & ","
Next
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", csvFile, False)
#End Region

Here are a few options to consider, for loading data from a CSV to a DGV.
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
End Class

You must try this code.
OpenButton
Dim OpenFileDialog1 As New OpenFileDialog()
Dim constr As String
Dim con As OleDb.OleDbConnection
Try
OpenFileDialog1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm;"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.txtOpen.Text = OpenFileDialog1.FileName
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDb.OleDbConnection(constr)
con.Open()
cboSheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
cboSheet.DisplayMember = "TABLE_NAME"
cboSheet.ValueMember = "TABLE_NAME"
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Load Button
Dim constr As String
Dim dt As DataTable
Dim con As OleDbConnection
Dim sda As OleDbDataAdapter
Dim row As DataRow
Try
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDbConnection(constr)
sda = New OleDbDataAdapter("Select * from [" + cboSheet.SelectedValue + "]", con)
dt = New DataTable
sda.Fill(dt)
For Each row In dt.Rows
DataGridView3.DataSource = dt
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I hope it will works! :)

Related

Export data to excel from sql server database using Date column in vb.net

I want to make a program that will query my data in sql server and export to excel , i have 2 txtbox in my form. txtFrom_Date and txtTo_Date, 1 btnGenerateReport button. User will enter the starting date and the until date in txtbox and when click btnGenerate it will auto export the data to excel for the specified date.
below is my whole code in report form:
when i run my program and type in txtFrom_Date 2018-02-21 and txtTo_Date 2018-02-21 i got an error message "incorrect syntaxt near '2018'. but when i check my database the format is just like that.
Please help me how to solve this thank you .
'NOTE before coding export excel function must add reference first in
project properties(microsoft excel 2012)
'References that we need
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO.Directory
Imports Microsoft.Office.Interop.Excel 'Before you add this reference
to your project,
' you need to install Microsoft Office and find last version of this
file.
Imports Microsoft.Office.Interop
Public Class Report
Dim dataAdapter As New SqlClient.SqlDataAdapter()
Dim dataSet As New DataSet
Dim command As New SqlClient.SqlCommand
Dim datatableMain As New System.Data.DataTable()
Dim connection As New SqlClient.SqlConnection("SERVER=L4SMTDB01\SMTDBS02;DATABASE=SMT_IT;user=sa;pwd=qwerty;")
Private Sub ReleaseObject(ByVal o As Object)
Try
While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
End While
Catch
Finally
o = Nothing
End Try
End Sub
Private Sub btnGenerateReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateReport.Click
' command.CommandText = String.Format("Select * from ComponentCheckerSystem where Last_Update between " & DateTimePicker1.Value.Date.ToOADate() & " and " & DateTimePicker2.Value.Date.ToOADate() & "")
' command.CommandText = String.Format("Select * from ComponentCheckerSystem where Last_Update >= ''" & txtFromDate.Text & "'' and Last_Update <= ''" & txtToDate.Text & "''")
'Assign your connection string to connection object
command.Connection = connection
command.CommandType = CommandType.Text
'' 'You can use any command sel
command.CommandText = String.Format("Select * from ComponentCheckerSystem where Last_Update between ''" & txtFromDate.Text & "'' and ''" & txtToDate.Text & "''")
dataAdapter.SelectCommand = command
connection.Close()
Dim f As FolderBrowserDialog = New FolderBrowserDialog
Try
If f.ShowDialog() = DialogResult.OK Then
'This section help you if your language is not English.
System.Threading.Thread.CurrentThread.CurrentCulture = _
System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
'Fill data to datatable
connection.Open()
dataAdapter.Fill(datatableMain)
connection.Close()
'Export the Columns to excel file
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
'Export the rows to excel file
For Each dr In datatableMain.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
'Set final path
Dim fileName As String = "\Summary of Operator Scan Wrong Items" + ".xls" 'just set the file Name
Dim finalPath = f.SelectedPath + fileName
txtPath.Text = finalPath
oSheet.Columns.AutoFit()
'Save file in final path
oBook.SaveAs(finalPath, XlFileFormat.xlWorkbookNormal, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
'Release the objects
ReleaseObject(oSheet)
oBook.Close(False, Type.Missing, Type.Missing)
ReleaseObject(oBook)
oExcel.Quit()
ReleaseObject(oExcel)
'Some time Office application does not quit after automation:
'so i am calling GC.Collect method.
GC.Collect()
MessageBox.Show("Export done successfully!")
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)
End Try
End Sub
Private Sub Report_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.CustomFormat = "YYYY-MMMM-DD"
DateTimePicker2.CustomFormat = "YYYY-MMMM-DD"
End Sub
End Class
Never trust what a user will put in a text box. It could be very bad for your database. Learn to use parameters. This will protect your DB and save headaches formatting you SQL Strings. Add 2 DateTimePickers to your form.
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "Select * from ComponentCheckerSystem where Last_Update between #FromDate AND #ToDate;"
command.Parameters.Add("#FromDate", SqlDbType.Date).Value = DateTimePicker1.Value.Date
command.Parameters.Add("#ToDate", SqlDbType.Date).Value = DateTimePicker2.Value.Date
How about this?
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Orders"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataGridView1_Click(sender As Object, e As EventArgs) Handles DataGridView1.Click
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub
End Class

Error when updating image in ms access

When I update the image in ms access i get this error:
coulddn't find d/bin/debug/openfilediloge1
and when I choose another image I get
couldn't save currently lockedby another user
my code as follow.
Private Sub Btnedit_Click(sender As Object, e As EventArgs) Handles Btnedit.Click
'Dim d As New DAL
'd.Dataedit("delete from labdetails")
'Pic.Image = Nothing
'MsgBox("من فضلك اختر صورة")
' btnsave_Click(Nothing, Nothing)
Try
Dim fsreader As New FileStream(dlgpics.FileName, FileMode.Open, FileAccess.Read)
Dim breader As New BinaryReader(fsreader)
Dim imgbuffer(fsreader.Length) As Byte
breader.Read(imgbuffer, 0, fsreader.Length)
fsreader.Close()
Dim strsql As String
Dim acscmd As New OleDbCommand
Dim con As New OleDbConnection
con = New OleDbConnection(("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath() & "\lab2015.accdb;Jet OLEDB:Database Password=mak;"))
strsql = "update labdetails set labnme=#labnme,labspecial=#labspecial,labadress=#labadress,labphone=#labphone,labtime=#labtime,lablogo=#lablogo,labprint=#labprint,labnameenglish=#labnameenglish,labspecialenglish=#labspecialenglish"
acscmd.CommandText = strsql
acscmd.Connection = con
acscmd.Parameters.AddWithValue("#labnme", txtlabname.Text)
acscmd.Parameters.AddWithValue("#labspecial", txtspeciality.Text)
acscmd.Parameters.AddWithValue("#labadress", txtadress.Text)
acscmd.Parameters.AddWithValue("#labphone", txtphone.Text)
acscmd.Parameters.AddWithValue("#labtime", txttime.Text)
acscmd.Parameters.AddWithValue("#lablogo", imgbuffer)
' If printchck.Checked = True Then
acscmd.Parameters.AddWithValue("#labprint", printchck.Checked)
acscmd.Parameters.AddWithValue("#labnameenglish", Txtlab.Text)
acscmd.Parameters.AddWithValue("#labspecialenglish", txtspecial.Text)
' Else
' acscmd.Parameters.AddWithValue("#labprint", "No")
' End If
con.Open()
acscmd.ExecuteNonQuery()
acscmd.Dispose()
Me.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
labdetails_Load(Nothing, Nothing)
End Sub

How to select an excel data Table using a drop downlist value

I am working on an application that uses excel files as its data source. I would love the DataGridView to populate with the columns of a sheet when a worksheet name is selected from the drop down list.
Here is what I have tried doing:
Imports System.Data.OleDb
Public Class Form101
Public cn As New OleDbConnection
Public cm As New OleDbCommand
Public da As OleDbDataAdapter
Dim comb As String
Public dt As New DataTable
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Comb1.SelectedIndexChanged
comb = Comb1.SelectedText
End Sub
Public Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "Date"
.Columns(1).HeaderText = "Qty brought"
.Columns(2).HeaderText = "Qty sold"
.Columns(3).HeaderText = "Goods balance"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\toojah app\Stock card.xls; Extended Properties= Excel 8.0;"
cn.Open()
FillDataGridView("select * FROM ['" & comb & "'] ")
End Sub
End Class
Try something like this. The first function will collect all of the columns and records in your excel file and place it into a datatable. Then If you wanted to add additional columns to the datable you can do it in the Public Sub CreateDataGridView. This has been tested and works.
Friend Shared Function BuildDatatable () as datatable
Dim dt As New DataTable
Dim Conn As System.Data.OleDb.OleDbConnection
Dim cmd As System.Data.OleDb.OleDbDataAdapter
dim MyFile as string = "C:\toojah app\Stock card.xls"
Conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyFile + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
Conn.Open()
Dim dtSheets As DataTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & drSheet("TABLE_NAME").ToString() & "]", Conn)
cmd.TableMappings.Add("Table", "Net-informations.com")
cmd.Fill(dt)
Conn.Close()
Next
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
'This is used to pass the function datatable as a dt to then pass to the public sub as shown below.
Dim dt As DataTable = BuildDatatable
Public Sub CreateDataGridView(dt)
Dim newColumn As New Data.DataColumn("ComeColumnName", GetType(System.String))
newColumn.DefaultValue = "YourValues"
dt.Columns.Add(newColumn)
DataGridView1.DataSource = dt
End Sub

Import excel worksheet into vb.net

I have got an excel worksheet which actually calculates the loan... If we input the amount and no. of years,it gives us a list of all the EMI's to be made in the coming years.
My boss wants to integrate that excel worksheet into vb.net form....How can I do so? Please help me....
In your form add a DataGrid "GridControl1" and a button "BtnImport_Click :
In your button BtnImport_Click add this code
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Excel files |*.xls;*.xlsx"
dialog.InitialDirectory = "C:\"
dialog.Title = "Veuillez sélectionner le fichier à importer"
'Encrypt the selected file. I'll do this later. :)
If dialog.ShowDialog() = DialogResult.OK Then
Dim dt As DataTable
dt = ImportExceltoDatatable(dialog.FileName)
GridControl1.DataSource = dt
GridControl1.Visible = True
MsgBox(" done ! ", MsgBoxStyle.Information)
End If
End Sub
And add this function in your form :
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName) ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
Hop that help you

Image upload to and download from SQL using VB.Net + Image downloads incorrectly

Imports System
Imports System.Data.SqlClient
Imports System.IO
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Read the file and convert it to Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype based on File Extension
Select Case ext
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes() As Byte = br.ReadBytes(fs.Length)
lblMessage.Text = bytes.ToString 'System.Text.Encoding.Unicode.GetString(bytes)
'insert the file into database
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
Try
con.Open()
Dim strQuery As String = "insert into uploadedImages (Name, ContentType, Data) values ('" & filename & "','" & contenttype & "','"
Dim bytesLength As Integer = bytes.Length - 1
For i As Integer = 0 To bytesLength
strQuery = strQuery & bytes(i)
Next
strQuery = strQuery & "')"
Dim cmd As New SqlCommand(strQuery)
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
con.Dispose()
End Try
' InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully" '& System.Text.ASCIIEncoding.ASCII.GetString(bytes)
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." & " Upload Image JPG or PNG formats"
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function
' code to retrieve image
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes As String = CType(dt.Rows(0)("Data"), String)
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
' convert a string to a byte array
Dim encoding As New System.Text.UTF8Encoding()
Response.BinaryWrite(encoding.GetBytes(dt.Rows(0)("Data")))
Response.Flush()
Response.End()
End Sub
Protected Sub btn_download_Click(sender As Object, e As EventArgs) Handles btn_download.Click
Dim strQuery As String = "select Name, ContentType, Data from uploadedImages where id=12"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("12", SqlDbType.Int).Value = 1
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Sub
End Class
The image downloads but the file is corrupted , I think the problem is when retrieving the string from the database and turning it into bytes ... Appreciate any help