Importing PDF into MS SQL - sql-server

I'm sorry for the log post but I am about to pull my hair out. I am attempting to import a PDF into a database.
The main error I am getting is: "Implicit conversion from data type varchar to varbinary(MAX) is not allowed. Use the CONVERT function to run this query."
Some of the coding included below is for a SEARCH function that is not yet completed. Please disregard that area of coding.
Basically I am loading a PDF in the AxAcroPDF1 box. This works great. It then pre-fills out a few of the textboxes. User inputs the Broker Load Number than hits save and a openfiledialog opens and the file is chosen to be imported. This then is where the failed import happens and the error above is given. I have tried many different avenues but always ending up with the same result. I am at a complete and total loss.
Table structure is as follows:
ID, int, NOT NULL IDENTITY(1,1) PRIMARY KEY,
BROKER_LOAD_NUMBER nvarchar(15) NOT NULL,
PDF_FILENAME,nvarchar(50) NOT NULL,
PETS_LOAD_NUMBER nvarchar(10) NOT NULL,
PAPERWORK varbinary(MAX) NOT NULL
My FULL code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
End Sub
Private Sub btnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
Private Sub SearchResult()
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
'SQL to get specific data from the Documents_Table
cmd.Parameters.Clear()
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
End Sub
Private Sub LbllSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
Dim Extension As String = Path.GetExtension(sFileToUpload)
upLoadImageOrFile(sFileToUpload, "PDF")
upLoadImageOrFile(sFileToUpload, Extension)
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf');"
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", data)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub upLoadImageOrFile(sFilePath As String, sFileType As String)
Dim cmd As New SqlCommand
Dim Data As Byte()
Dim sFileName As String
Dim qry As String
Try
'Read Image Bytes into a byte array
Data = ReadFile(sFilePath)
sFileName = Path.GetFileName(sFilePath)
'Set insert query
qry = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf')"
'Initialize SqlCommand object for insert.
cmd = New SqlCommand(qry, cmd.Connection)
'We are passing File Name and Image byte data as sql parameters.
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", Data)
cmd.ExecuteNonQuery()
MessageBox.Show("File uploaded successfully")
Catch ex As Exception
MessageBox.Show("File could not uploaded")
End Try
End Sub
Private Function ReadFile(sFilePath As String) As Byte()
Throw New NotImplementedException()
End Function
End Class

Related

"System.OutOfMemoryException: 'Out of memory.'" when reading image from SQL Server

I have images assigned to every button in my VB.NET form, the images come from SQL Server. The data type is varbinary(MAX).
This is my code:
Using con As New SqlConnection("con string")
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 3
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Image")) Then
Boton3.Text = myreader("Item")
Boton3.Enabled = myreader("ONOFF")
Dim ImgSql() As Byte = DirectCast(myreader("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
con.Close()
End Using
Else
Boton3.Text = myreader("Item")
Boton3.BackgroundImage = Nothing
Boton3.Enabled = myreader("ONOFF")
End If
End Using
End Using
End Using
The platform is 64bit. I'm thinking it might have to do with not disposing properly, but I'm not sure since I'm new to coding.
EDIT SHOWING NEW CODE AND HOW I RETRIVE MORE THAN ONE RECORD:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(1)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton1.Text = dt.Rows(0)("Articulo").ToString
Boton1.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton1.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton1.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
Dim dt2 As DataTable
Try
dt2 = GetInventoryDataByID(2)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt2.Rows.Count > 0 Then
Boton2.Text = dt2.Rows(0)("Articulo").ToString
Boton2.Enabled = CBool(dt2.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt2.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt2.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton2.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton2.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT Imagen, Articulo, ONOFF FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("CON STRING"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
End Class
You don't want to hold a connection open while you update the user interface. Separate you user interface code from your database code.
If you put a comma at the end of the first line of the outer Using block, both the command and the connection are included in same block. Saves a bit of indenting.
You are passing an integer to the #ID parameter but you have set the SqlDbType as a VarChar. Looks like a problem. I changed the SqlDbType to Int.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(3)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton3.Text = dt.Rows(0)("Item").ToString
Boton3.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton3.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using con As New SqlConnection("con string"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
EDIT Add Dispose on image
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
End If
I resolved this issue by simply not using buttons. Instead I used pictureboxes as buttons and that resolved the issue. Im guesssing the problem is that buttons don't allow as much memory as pictureboxes.

MultipleActiveResultSets for SQL Server and VB.NET application

I am trying to get multiple data sets from SQL Server using a VB.NET application. The problem that every time I try to execute the query,
I get this message:
Cannot change property 'ConnectionString'. The current state of the connection is open
Then I tried to fix it by enabling MARS
<connectionStrings>
<add name="ConString"
providerName="System.Data.SqlClient"
connectionString="Data Source=my-PC;Initial Catalog=Project;Persist Security Info=True; MultipleActiveResultSets=true;User ID=user;Password=*****" />
</connectionStrings>
This is my code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj, body
obj = TextBox1.Text
body = TextBox2.Text
For Each mail In getemail()
Send_mail(mail, obj, body, getattachment(mail))
Next
MsgBox("Traitement effectué")
End Sub
Function getemail() As List(Of String)
Dim strMailTo As New List(Of String)
Dim SQL As String = "Select EMail FROM [USER] WHERE EMail Is Not NULL And MatriculeSalarie Is Not NULL And [EMail] <> '' and EtatPaie = 3 and BulletinDematerialise = 1 "
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
Dim dr As DataRow
Try
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Using sda As New SqlDataAdapter(cmd)
Using ds As New DataTable()
sda.Fill(ds)
sqLdr = cmd.ExecuteReader()
For i = 0 To ds.Rows.Count - 1
dr = ds.Rows(i)
strMailTo.Add(dr("EMail"))
Next
End Using
End Using
Return strMailTo
sqLdr.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
closeCon()
Return strMailTo
End Function
Function getattachment(email) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Dim mat As String
mat = ""
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
Dim file()
sqLdr = cmd.ExecuteReader()
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
file = IO.Directory.GetFiles(Dir, mat.Substring(1) & "*.pdf")
sqLdr.Close()
Return file
End Function
If all you are going to do is show a message box in a Catch, don't do it in the database code. Let the error bubble up to the user interface code and put the Try around where the method is called.
Do not declare variables without a DataType. The button code with Option Infer on sets the type of obj and body.
Private ConStr As String = "Your connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj = TextBox1.Text
Dim body = TextBox2.Text
Dim emails As New List(Of String)
Try
emails = getemail()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error retrieving email list")
Exit Sub
End Try
For Each email In emails
Try
Send_mail(email, obj, body, getattachment(email))
Catch ex As Exception
MessageBox.Show(ex.Message, "Error getting attachments")
End Try
Next
MessageBox.Show("Traitement effectué")
End Sub
Parameters used by Sub and Function must have a DataType.
I don't know what you are doing here.
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
Each iteration will overwrite the previous value of mat. I can only assume that you expect only a single value, in which case you can use ExecuteScalar to get the first column of the first row of the result set. Don't do anything with the data until after the connection is closed. Just get the raw data and close (End Using) the connection. Manipulate the data later.
Always use Parameters. Parameters are not treated as executable code by the database server. They are simply values. An example of executable code that could be inserted is "Drop table [USER];" where the value of a parameter belongs. Oops!
Function getemail() As List(Of String)
Dim SQL As String = "Select EMail FROM [USER]
WHERE EMail Is Not NULL
And MatriculeSalarie Is Not NULL
And [EMail] <> ''
And EtatPaie = 3
And BulletinDematerialise = 1;"
Dim dt As New DataTable
Using con As New SqlConnection("Your connection string"),
cmd As New SqlCommand(SQL, con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Dim strMailTo As New List(Of String)
strMailTo = (From row As DataRow In dt.AsEnumerable
Select row.Field(Of String)(0)).ToList
Return strMailTo
End Function
Function getattachment(email As String) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim mat As String
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand(SQL, con)
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = email
con.Open()
mat = cmd.ExecuteScalar().ToString()
End Using
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
'Your original code was fine, no need for searchPattern.
'I added this so you could see if your search pattern was what you expected.
Dim searchPattern = mat.Substring(1) & "*.pdf"
Debug.Print(searchPattern) 'Appears in the Immediate window
Dim file = IO.Directory.GetFiles(Dir, searchPattern)
Return file
End Function

saved image file showing twice when I refresh combobox list

So I am working with blobs in visual basic, and I'm saving image files to a database. When I save them I have their name.jpg showing up in a combobox, but when I save another image and it refreshes the list, the name of the previous image shows twice. I'm not sure how I managed that. I am new to this so don't look down on me too much!
When the button on my form is clicked:
Private Sub btnSaveBlob_Click(sender As Object, e As EventArgs) Handles btnSaveBlob.Click
SaveBlobToDatabase()
refreshBlobList()
End Sub
My methods:
Private Sub SaveBlobToDatabase()
GetCompleteFilePath()
Dim BLOB() As Byte
Dim FileStream As New IO.FileStream _
(CompleteFilePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim reader As New IO.BinaryReader(FileStream)
BLOB = reader.ReadBytes(CInt(My.Computer.FileSystem.GetFileInfo(CompleteFilePath).Length))
FileStream.Close()
reader.Close()
Dim SaveDocCommand As New SqlCommand
SaveDocCommand.Connection = conn
SaveDocCommand.CommandText = "INSERT INTO DocumentStorage" &
"(FileName, DocumentFile)" &
"VALUES (#FileName, #DocumentFile)"
Dim FileNameParameter As New SqlParameter("#FileName", SqlDbType.NChar)
Dim DocumentFileParameter As New SqlParameter("#DocumentFile", SqlDbType.Binary)
SaveDocCommand.Parameters.Add(FileNameParameter)
SaveDocCommand.Parameters.Add(DocumentFileParameter)
FileNameParameter.Value =
CompleteFilePath.Substring(CompleteFilePath.LastIndexOf("\") + 1)
DocumentFileParameter.Value = BLOB
Try
SaveDocCommand.Connection.Open()
SaveDocCommand.ExecuteNonQuery()
MessageBox.Show(FileNameParameter.Value.ToString &
"saved to database.", "BLOB Saved!", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Save Failed",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
SaveDocCommand.Connection.Close()
End Try
End Sub
Private Sub refreshBlobList()
Dim GetBlobListCommand As New SqlCommand("SELECT FileName FROM DocumentStorage", conn)
Dim reader As SqlDataReader
GetBlobListCommand.Connection.Open()
reader = GetBlobListCommand.ExecuteReader
While reader.Read
lstBlob.Items.Add(reader(0))
End While
reader.Close()
GetBlobListCommand.Connection.Close()
If lstBlob.Items.Count > 0 Then
lstBlob.SelectedIndex = 0
End If
End Sub
Objects in .net that show you a .Dispose method should be disposed. They have unmanaged code and need to properly release things. Connections, Commands, Streams, and Readers fall into this group. Luckily .net has provided Using...End Using blocks that handle this for us even if there is an error. For this reason, these objects should be kept local to the methods where they are used.
As much as possible, methods should perform a single task. I pulled out the code to create the byte array to a separate Function. I also split the data access code from the user interace code. You may want to put the data access code in a separate class. This would come in handy if you want to change to a web app, for example.
In the data access code:
You can pass the connection string directly to the constructor of the connection. Likewise, pass the CommandText and Connection directly to the constructor of the command. The .Add method of the .Parameters collection will create a new parameter from the name and datatype passed to it. You can also set the value on the same line.
Private ConStr As String = "Your connection string"
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim RowsAdded As Integer
Try
RowsAdded = SaveBlobToDatabase()
Catch ex As Exception
MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
If RowsAdded = 1 Then
MessageBox.Show("Saved to database.", "BLOB Saved!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Function SaveBlobToDatabase() As Integer
Dim RowsAdded As Integer
Dim CompleteFilePath As String = GetCompleteFilePath()
Using conn As New SqlConnection(ConStr),
SaveCommand As New SqlCommand("INSERT INTO DocumentStorage(FileName, DocumentFile) VALUES(#FileName, #DocumentFile);", conn)
SaveCommand.Parameters.Add("#FileName", SqlDbType.NChar).Value = Path.GetFileName(CompleteFilePath) 'Requires Imports System.IO
SaveCommand.Parameters.Add("#DocumentFile", SqlDbType.Binary).Value = GetByteArrayFromFile(CompleteFilePath)
conn.Open()
RowsAdded = SaveCommand.ExecuteNonQuery()
End Using
Return RowsAdded
End Function
Private Function GetByteArrayFromFile(FullPath As String) As Byte()
Dim Blob() As Byte
Using FileStream As New IO.FileStream(FullPath, IO.FileMode.Open, IO.FileAccess.Read),
reader As New IO.BinaryReader(FileStream)
Blob = reader.ReadBytes(CInt(My.Computer.FileSystem.GetFileInfo(FullPath).Length))
End Using
Return Blob
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lstBlob.Items.Clear()
lstBlob.DataSource = refreshBlobList()
lstBlob.DisplayMember = "FileName"
If lstBlob.Items.Count > 0 Then
lstBlob.SelectedIndex = 0
End If
End Sub
Private Function refreshBlobList() As DataTable
Dim dt As New DataTable
Using conn As New SqlConnection(ConStr),
GetBlobListCommand As New SqlCommand("SELECT FileName FROM DocumentStorage", conn)
conn.Open()
dt.Load(GetBlobListCommand.ExecuteReader)
End Using
Return dt
End Function

How to import text file in vb.net and insert into SQL server?

I'm trying to import a text file into an SQL server. I need to read data inside the file when I upload it and send all the data to an SQL server. Of course inside the SQL I have primary keys where it's going to increment when a new line of data is finished.
HELP!
With Cinchoo ETL - an open source ETL framework, you can load the entire file to database with few lines of code as below (the code is in c#, hope you can translate it to vb.net)
string connectionstring =
#"Data Source=(localdb)\v11.0;Initial Catalog=TestDb;Integrated Security=True";
using (SqlBulkCopy bcp = new SqlBulkCopy(connectionstring))
{
using (var dr = new ChoCSVReader<Customer>
("Cust.csv").WithFirstLineHeader().AsDataReader())
{
bcp.DestinationTableName = "dbo.Customers";
bcp.EnableStreaming = true;
bcp.BatchSize = 10000;
bcp.BulkCopyTimeout = 0;
bcp.NotifyAfter = 10;
bcp.SqlRowsCopied += delegate (object sender, SqlRowsCopiedEventArgs e)
{
Console.WriteLine(e.RowsCopied.ToString("#,##0") + " rows copied.");
};
bcp.WriteToServer(dr);
}
}
For more details, visit the codeproject article
Disclosure: I'm the author of this library.
This is an interesting question. I did this a looonnngggg time ago. See the code below, for a solution to your question.
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
Also, see ALL the code below, for several similar, and related, tasks. Notice, I added a few comments, but not too many...
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Imports System.Configuration
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 Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
"initial catalog=NORTHWIND;Trusted_Connection=True"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM [Order Details]"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub
Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object,
ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
If e.ColumnIndex = DataGridView1.Columns(3).Index _
AndAlso e.Value IsNot Nothing Then
'
If CInt(e.Value) < 10 Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.ForeColor = Color.LightGoldenrodYellow
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
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim SQLConnectionString As String = "Data Source=Excel-PC\SQLEXPRESS;" & _
"Initial Catalog=Northwind;" & _
"Trusted_Connection=True"
' Open a connection to the AdventureWorks database.
Using SourceConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
SourceConnection.Open()
' Perform an initial count on the destination table.
Dim CommandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.Orders;", _
SourceConnection)
Dim CountStart As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", CountStart)
' Get data from the source table as a AccessDataReader.
'Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
' "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
' "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & "C:\Users\Excel\Desktop\" & ";" & _
"Extended Properties=""Text;HDR=No"""
Dim TextConnection As New System.Data.OleDb.OleDbConnection(ConnectionString)
Dim TextCommand As New OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection)
TextConnection.Open()
Dim TextDataReader As OleDbDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess)
' Open the destination connection.
Using DestinationConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
DestinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using BulkCopy As SqlBulkCopy = _
New SqlBulkCopy(DestinationConnection)
BulkCopy.DestinationTableName = _
"dbo.Orders"
Try
' Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the AccessDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
TextDataReader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim CountEnd As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
'Console.WriteLine("Ending row count = {0}", CountEnd)
'Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
End Using
End Using
'Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
'Dim TextLine As String
'If System.IO.File.Exists(FILE_NAME) = True Then
' Dim objReader As New System.IO.StreamReader(FILE_NAME)
' Do While objReader.Peek() <> -1
' TextLine = TextLine & objReader.ReadLine() & vbNewLine
' Loop
'Else
' MsgBox("File Does Not Exist")
'End If
'Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
'Dim cmd As New SqlCommand
'cmd.Connection = cn
'cmd.Connection.Close()
'cmd.Connection.Open()
'cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
'cmd.ExecuteNonQuery()
'cmd.Connection.Close()
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
' Define the Column Definition
Dim dt As New DataTable()
dt.Columns.Add("OrderID", GetType(Integer))
dt.Columns.Add("CustomerID", GetType(String))
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("OrderDate", GetType(Date))
dt.Columns.Add("RequiredDate", GetType(Date))
dt.Columns.Add("ShippedDate", GetType(Date))
dt.Columns.Add("ShipVia", GetType(Integer))
dt.Columns.Add("Freight", GetType(Decimal))
dt.Columns.Add("ShipName", GetType(String))
dt.Columns.Add("ShipAddress", GetType(String))
dt.Columns.Add("ShipCity", GetType(String))
dt.Columns.Add("ShipRegion", GetType(String))
dt.Columns.Add("ShipPostalCode", GetType(String))
dt.Columns.Add("ShipCountry", GetType(String))
Using cn = New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
cn.Open()
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\Users\Excel\Desktop\OrdersTest.csv")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = dt.NewRow()
For currColumn = 0 To dt.Columns.Count - 1
sqlColumnDataType = dt.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
dt.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
'Return False
Finally
dr = Nothing
End Try
End While
Using copy As New SqlBulkCopy(cn)
copy.DestinationTableName = "[dbo].[Orders]"
copy.WriteToServer(dt)
End Using
End Using
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
'Dim cnn As SqlConnection
'Dim connectionString As String
'Dim sql As String
'connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
'"initial catalog=NORTHWIND;Trusted_Connection=True"
'cnn = New SqlConnection(connectionString)
'cnn.Open()
'GetCsvData("C:\Users\Excel\Desktop\OrdersTest.csv", dbo.Orders)
End Sub
Public Shared Function GetCsvData(ByVal CSVFileName As String, ByRef CSVTable As DataTable) As Boolean
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName)
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = CSVTable.NewRow()
For currColumn = 0 To CSVTable.Columns.Count - 1
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
CSVTable.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
Return False
Finally
dr = Nothing
End Try
End While
reader.Close()
reader.Dispose()
Return True
End Function
Private Sub DataGridView1_RowValidating(ByVal sender As Object, ByVal e As DataGridViewCellCancelEventArgs)
End Sub
End Class
One more to try . . .
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file As String = "Import.txt"
Dim path As String = "C:\Users\path_to_text_file\"
Dim ds As New DataSet
Try
If IO.File.Exists(IO.Path.Combine(path, file)) Then
Dim ConStr As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
path & ";Extended Properties=""Text;HDR=No;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & _
file, conn)
da.Fill(ds, "TextFile")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class

Verify login data from username and password columns

I wrote the following function to verify log in data for user, but so far its not working as it should and I am sure there is something wrong with it:
Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles button2.Click
If loginpasswordtx.Text.Length > 1 And loginpasswordtx.Text.Length > 1 And My.Settings.SQLConnectionString.Length > 5 Then
Try
Dim cnn As New SqlConnection(My.Settings.SQLConnectionString)
Dim cmd = New SqlCommand("SELECT AppUser,AppUserPass FROM OrderAppUsers WHERE AppUser=#AppUser AND AppUserPass=#AppUserPass", cnn)
cmd.Parameters.Add(New SqlParameter("#AppUser", createuserAppUser.Text))
cmd.Parameters.Add(New SqlParameter("#AppUserPass", MD5StringHash(loginpasswordtx.Text)))
cnn.Open()
Dim obj As Object = cmd.ExecuteScalar()
If obj = Nothing Then
MsgBox("Faild to Log in, check your log in info")
cnn.Close()
Return
End If
cnn.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Return
End Try
MsgBox("Logged in Successfully")
End If
End Sub
All I get is a null obj even though user and pass exist in the table.
the following code is for adding new users
Try
Dim cnnstring As String = String.Format("Server={0};Database={1};Trusted_Connection=True;", createuserServerTx.Text, createuserDatabaseTx.Text)
Dim cnn As New SqlConnection(cnnstring)
Dim cmd As New SqlCommand("INSERT INTO OrderAppUsers VALUES (#AppUser, #AppUserPass)", cnn)
cmd.Parameters.Add(New SqlParameter("#AppUser", createuserAppUser.Text))
cmd.Parameters.Add(New SqlParameter("#AppUserPass", MD5StringHash(createuserpassword.Text)))
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
MsgBox("User Crated Successfully")
LayoutControl1.Visibility = Windows.Visibility.Collapsed
My.Settings.SQLConnectionString = cnnstring
My.Settings.Save()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
and the function to generate a custom hash
Private Function MD5StringHash(ByVal strString As String) As String
Dim MD5 As New MD5CryptoServiceProvider
Dim Data As Byte()
Dim Result As Byte()
Dim R As String = ""
Dim Temp As String = ""
Data = Encoding.ASCII.GetBytes(strString)
Result = MD5.ComputeHash(Data)
For i As Integer = 0 To Result.Length - 1
Temp = Hex(3 * Result(i) + 1)
If Len(Temp) = 1 Then Temp = "0" & Temp
R += Temp
Next
Return R
End Function
Try the following when adding parameter
cmd.Parameters.AddWithValue("#AppUser", createuserAppUser.Text)
cmd.Parameters.AddWithValue("#AppUserPass", MD5StringHash(loginpasswordtx.Text))
or just stick with what you did but a little different than yours,
cmd.Parameters.Add("#AppUser", SqlDbType.VarChar)
cmd.Parameters("#AppUser").Value = createuserAppUser.Text
cmd.Parameters.Add("#AppUserPass", SqlDbType.VarChar)
cmd.Parameters("#AppUserPass").Value = MD5StringHash(loginpasswordtx.Text)
by the way, when using ExecuteScalar() it only returns single value. So your query can be written as
SELECT COUNT(*)
FROM OrderAppUsers
WHERE AppUser=#AppUser AND AppUserPass=#AppUserPass
and you can use int variable to store its value
Dim obj As int = Cint(cmd.ExecuteScalar())
so the possible values are 0 or the total number of records return.
If obj = 0 Then
MsgBox("Faild to Log in, check your log in info")
'' other codes
End If
and by refractoring your code, use Using -Statement
Using cnn As New SqlConnection(My.Settings.SQLConnectionString)
Using cmd = New SqlCommand("SELECT COUNT(*) FROM OrderAppUsers WHERE AppUser=#AppUser AND AppUserPass=#AppUserPass", cnn)
cmd.Parameters.AddWithValue("#AppUser", createuserAppUser.Text)
cmd.Parameters.AddWithValue("#AppUserPass", MD5StringHash(loginpasswordtx.Text))
cmd.CommandType = CommandType.Text
Try
cnn.Open()
Dim obj As int = Cint(cmd.ExecuteScalar())
If obj = 0 Then
MsgBox("Faild to Log in, check your log in info")
Else
MsgBox("Logged in Successfully")
End If
Catch(ex As SqlException)
MsgBox(ex.Message.ToString())
End Try
End Using
End Using
I checked your code in my local system and it is working fine i mean i was able to validate its return true i analysis and found its return false only when i am adding one space on password text before encrypt can u check in database value is space adding into password value or can u post your encrypt code

Resources