How do I Iterate Through DataTable and Decrypt a field? - vb.net

Good-day,
I need help with iterating through a DataTable (dbTable) and decrypting a particular field (ccNumber) before assigning its items to a Listview control (ListViewRecords).
I've already used the decryption code below elsewhere in my project on a Textbox with success, but can't figure out how to do it with the DataTable. Your assistance would be greatly appreciated, thanks.
HERE'S THE DECRYPTION CODE:
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Try
DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
DES.Mode = System.Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(TextBoxCard.Text)
TextBoxCard.Text = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
MessageBox.Show("The following error(s) have occurred: " & ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
HERE'S THE CODE TO QUERY THE DB AND FILL THE LISTVIEW:
Private Sub loadRecords()
'FOR MySQL DATABASE USE
Dim dbConn As New MySqlConnection
Dim dbTable As New DataTable
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
Dim dbAdapter As New MySqlDataAdapter
dbTable.Clear()
Try
If dbConn.State = ConnectionState.Closed Then
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"ORDER BY nameCOMPANY ASC"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbTable)
End With
ListViewRecords.Items.Clear()
For i = 0 To dbTable.Rows.Count - 1
With ListViewRecords
.Items.Add(dbTable.Rows(i)("ccID"))
With .Items(.Items.Count - 1).SubItems
.Add(dbTable.Rows(i)("nameCOMPANY"))
.Add(dbTable.Rows(i)("ccNumber"))
.Add(dbTable.Rows(i)("ccExpireMonth"))
.Add(dbTable.Rows(i)("ccExpireYear"))
.Add(dbTable.Rows(i)("ccType"))
.Add(dbTable.Rows(i)("ccAuthorizedUseStart"))
.Add(dbTable.Rows(i)("ccAuthorizedUseEnd"))
.Add(dbTable.Rows(i)("ccLocation"))
.Add(dbTable.Rows(i)("cardholderSalutation"))
.Add(dbTable.Rows(i)("cardholderLastname"))
.Add(dbTable.Rows(i)("cardholderFirstname"))
.Add(dbTable.Rows(i)("ccZipcode"))
End With
End With
Next
Catch ex As MySqlException
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
End Sub

Put the decryption thing in a function:
Function Decrypt(ByVal ToDecrypt) as String
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim Hash As New System.Security.Cryptography.MD5CryptoServiceProvider
Try
DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(My.Settings.Key))
DES.Mode = System.Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(ToDecrypt)
return System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
return "Whatever failed message you want"
End Try
End Function
Then loop through your table like this and change the value:
for i as Integer = 0 to dbTable.Rows.Count - 1
dbTable.Rows(i)("ccNumber")) = Decrypt(dbTable.Rows(i)("ccNumber"))
This should work if I'm not totally off.

Related

Converting Access OLE object image to show in Datagridview vb.net

I'm trying to load data from an Access database into a DataGridView.
This is my access database - Image has long binary data
However, when I retrieve the data from the database and try to load it into the DataGridView, it shows this error:
I have 2 forms, this one is for adding to database:
This one is for showing the database in the DataGridView
Here's my code to add my uploaded image to database.
Dim fsreader As New FileStream(OpenFileDialog1.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 create As New OleDbCommand("INSERT INTO Officials ([officialname] , [age] , [birthdate] , [position] , [term], [status], [image] ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "' , '" & DateTimePicker1.Value & "' , '" & cb1 & "' , '" & TextBox3.Text & "' , '" & status & "' , #img )", con)
With create
.Parameters.Add("#on", OleDb.OleDbType.VarChar).Value = TextBox1.Text.Trim
.Parameters.Add("#age", OleDb.OleDbType.VarChar).Value = TextBox2.Text.Trim
.Parameters.Add("#bd", OleDb.OleDbType.VarChar).Value = DateTimePicker1.Value
.Parameters.Add("#pn", OleDb.OleDbType.VarChar).Value = cb1
.Parameters.Add("#tm", OleDb.OleDbType.VarChar).Value = TextBox3.Text.Trim
.Parameters.Add("#st", OleDb.OleDbType.VarChar).Value = status
.Parameters.Add("#img", OleDb.OleDbType.LongVarBinary).Value = imgbuffer
I can give you an example how to put images on a DataGridView from Access but you'll need to adapt to your reality.
Just add a DataGridView and create 2 columns, first as TextBoxColumn and second as ImageColumn.
The next step is to load data from access database, so use what you already have that is not shown in your post. It will be something like:
Dim GConn As New OleDbConnection("your connection string...")
Dim GCmd As New OleDbCommand()
Dim DtReader As OleDbDataReader
GCmd.Connection = GConn
GCmd.CommandText = "SELECT PhotoDescription, PhotoOLE FROM MY_TABLE;"
DtReader = GCmd.ExecuteReader ' DtReader will have all the rows from database
' For this test you need to load less than 100 records
dim iLine as integer=0
DataGridView1.rows.Add(100) ' add 100 rows to test
DtReader.Read ' read first record
Do
DataGridView1.Rows(iLine).Cells(0).Value=DtReader("PhotoDescription").ToString
DataGridView1.Rows(iLine).Cells(1).Value=CType(DtReader("PhotoOLE"), Byte())
iLine+=1
Loop while DtReader.Read
It's not necessary to store both birthdate and age, because one of them can be computed given a value for the other one.
You haven't provided enough code to identify the issue, but if the image data wasn't properly converted before storing it, that would cause an issue.
Below shows how to both insert and update data that contains an image, as well as how to retrieve the data. In the code below, you'll also find code that will create an Access database and a table.
Add a reference to Microsoft ADO Ext. 6.0 for DDL and Security
Note: This is required for the "CreateDatabase" function in the code below.
In VS menu, click Project
Select Add Reference...
Select COM
Check Microsoft ADO Ext. 6.0 for DDL and Security
The code is tested and fairly well-documented. Of particular importance are the following functions/methods:
GetImageAsByteArray
TblOfficialsExecuteNonQuery
TblOfficialsInsert
TblOfficialsGetData
Create a class (name: HelperAccess.vb)
Imports System.Data.OleDb
Imports System.IO
Public Class HelperAccess
Private _accessFilename As String = String.Empty
Private _connectionStr As String = String.Empty
Public ReadOnly Property AccessFilename
Get
Return _accessFilename
End Get
End Property
Sub New(accessFilename As String, Optional dbPassword As String = "")
'set value
_accessFilename = accessFilename
'create connection string
If Not String.IsNullOrEmpty(dbPassword) Then
_connectionStr = String.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", accessFilename, dbPassword)
Else
_connectionStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};", _accessFilename)
End If
End Sub
Public Function CreateDatabase() As String
Dim result As String = String.Empty
Dim cat As ADOX.Catalog = Nothing
Try
'create New instance
cat = New ADOX.Catalog()
'create Access database
cat.Create(_connectionStr)
'set value
result = String.Format("Status: Database created: '{0}'", _accessFilename)
Return result
Catch ex As Exception
'set value
result = String.Format("Error (CreateDatabase): {0}(Database: {1})", ex.Message, _accessFilename)
Return result
Finally
If cat IsNot Nothing Then
'close connection
cat.ActiveConnection.Close()
'release COM object
System.Runtime.InteropServices.Marshal.ReleaseComObject(cat)
cat = Nothing
End If
End Try
End Function
Public Function CreateTblOfficials() As String
Dim result As String = String.Empty
Dim tableName As String = "Officials"
Dim sqlText = String.Empty
sqlText = "CREATE TABLE Officials "
sqlText += "(ID AUTOINCREMENT not null primary key,"
sqlText += " [FullName] varchar(50) not null,"
sqlText += " [Birthdate] DateTime,"
sqlText += " [JobDescription] varchar(50) not null,"
sqlText += " [Term] varchar(50),"
sqlText += " [Status] varchar(50) not null,"
sqlText += " [Photo] Longbinary);"
Try
'create database table
ExecuteNonQuery(sqlText)
result = String.Format("Table created: '{0}'", tableName)
Catch ex As OleDbException
result = String.Format("Error (CreateTblOfficials - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
Catch ex As Exception
result = String.Format("Error (CreateTblOfficials): Table creation failed: '{0}'; {1}", tableName, ex.Message)
End Try
Return result
End Function
Private Function ExecuteNonQuery(sqlText As String) As Integer
Dim rowsAffected As Integer = 0
'used for insert/update
'create new connection
Using cn As OleDbConnection = New OleDbConnection(_connectionStr)
'open
cn.Open()
'create new instance
Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)
'execute
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Return rowsAffected
End Function
Public Function GetImageAsByteArray(filename As String) As Byte()
'read image from file and return as Byte()
Try
If Not String.IsNullOrEmpty(filename) AndAlso System.IO.File.Exists(filename) Then
Using fs As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim imageBytes(fs.Length) As Byte
'read image from file and put into Byte()
fs.Read(imageBytes, 0, fs.Length)
Return imageBytes
End Using
End If
Catch ex As Exception
Debug.WriteLine("Error (GetImageAsByteArray): " + ex.Message)
Throw
End Try
Return Nothing
End Function
Public Function TblOfficialsExecuteNonQuery(sqlText As String, fullName As String, birthdate As Date, jobDescription As String, term As String, status As String, imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
'create new connection
Using cn As OleDbConnection = New OleDbConnection(_connectionStr)
'open
cn.Open()
'create new instance
Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)
'OLEDB doesn't use named parameters in SQL. Any names specified will be discarded and replaced with '?'
'However, specifying names in the parameter 'Add' statement can be useful for debugging
'Since OLEDB uses anonymous names, the order which the parameters are added is important
'if a column is referenced more than once in the SQL, then it must be added as a parameter more than once
'parameters must be added in the order that they are specified in the SQL
'if a value is null, the value must be assigned as: DBNull.Value
With cmd.Parameters
.Add("!fullName", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(fullName), DBNull.Value, fullName)
.Add("!birthDate", OleDbType.Date).Value = birthdate
.Add("!jobDescription", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(jobDescription), DBNull.Value, jobDescription)
.Add("!term", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(term), DBNull.Value, term)
.Add("!status", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(status), DBNull.Value, status)
'set size to -1, otherwise it defaults to a maxium of 8000
.Add("!photo", OleDbType.VarBinary, -1).Value = imageBytes
End With
'ToDo: remove the following code that is for debugging
'For Each p As OleDbParameter In cmd.Parameters
'Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
'Next
'execute
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Return rowsAffected
End Function
Public Function TblOfficialsGetData() As DataTable
Dim dt As DataTable = New DataTable()
Dim sqlText As String = "SELECT * from Officials"
Try
'create new connection
Using con As OleDbConnection = New OleDbConnection(_connectionStr)
'open
con.Open()
'create new instance
Using cmd As OleDbCommand = New OleDbCommand(sqlText, con)
Using da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
'fill DataTable from database
da.Fill(dt)
End Using
End Using
End Using
Return dt
Catch ex As OleDbException
Debug.WriteLine("Error (TblOfficialsGetData - OleDbException) - " & ex.Message & "(" & sqlText & ")")
Throw ex
Catch ex As Exception
Debug.WriteLine("Error (TblOfficialsGetData) - " & ex.Message & "(" & sqlText & ")")
Throw ex
End Try
End Function
Public Function TblOfficialsInsert(fullName As String, birthdate As Date, jobDescription As String, term As String, status As String, imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
Dim sqlText As String = String.Empty
sqlText = "INSERT INTO Officials ([FullName], [BirthDate], [JobDescription], [Term], [Status], [Photo]) VALUES (?, ?, ?, ?, ?, ?);"
Try
'insert data to database
Return TblOfficialsExecuteNonQuery(sqlText, fullName, birthdate, jobDescription, term, status, imageBytes)
Catch ex As OleDbException
Debug.WriteLine("Error (TblOfficialsInsert - OleDbException) - " & ex.Message & "(" & sqlText & ")")
Throw ex
Catch ex As Exception
Debug.WriteLine("Error (TblOfficialsInsert) - " & ex.Message & "(" & sqlText & ")")
Throw ex
End Try
Return rowsAffected
End Function
Public Function TblOfficialsUpdate(fullName As String, birthdate As Date, jobDescription As String, term As String, status As String, imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
Dim sqlText As String = String.Empty
sqlText = "UPDATE Officials SET [FullName] = ?, [Birthdate] = ? , [JobDescription] = ?, [Term] = ?, [Status] = ?, [Photo] = ?;"
Try
'update data in database
Return TblOfficialsExecuteNonQuery(sqlText, fullName, birthdate, jobDescription, term, status, imageBytes)
Catch ex As OleDbException
Debug.WriteLine("Error (TblOfficialsUpdate - OleDbException) - " & ex.Message & "(" & sqlText & ")")
Throw ex
Catch ex As Exception
Debug.WriteLine("Error (TblOfficialsUpdate) - " & ex.Message & "(" & sqlText & ")")
Throw ex
End Try
Return rowsAffected
End Function
End Class
Usage
Create Access Database:
Private _helper As HelperAccess = Nothing
...
Dim sfd As SaveFileDialog = New SaveFileDialog()
sfd.Filter = "Access Database (*.accdb)|*.accdb|Access Database (*.mdb)|*.mdb"
If sfd.ShowDialog() = DialogResult.OK Then
'create new instance
_helper = New HelperAccess(sfd.FileName)
Dim result As String = _helper.CreateDatabase()
End If
Create Table
Private _helper As HelperAccess = Nothing
...
Dim result As String = _helper.CreateTblOfficials()
Insert data to database:
Private _helper As HelperAccess = Nothing
...
Dim imageBytes As Byte() = Nothing
imageBytes = System.IO.File.ReadAllBytes("C:\Temp\Images\Test1.jpg")
_helper.TblOfficialsInsert("Joe Smith", New Date(1986, 5, 20), "Captain", "2016-2030", "Active", imageBytes)
Get data from database:
Add a DataGridView to your form from the Toolbox (don't add any columns)
Private _dt As DataTable = New DataTable()
Private _helper As HelperAccess = Nothing
Private _source As BindingSource = New BindingSource()
...
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'set properties
DataGridView1.AllowUserToAddRows = False
DataGridView1.AllowUserToDeleteRows = False
'set data source
DataGridView1.DataSource = _source
End Sub
Private Sub GetData()
'get data from database
_dt = _helper.TblOfficialsGetData()
'set value
_source.DataSource = _dt
_source.ResetBindings(True)
End Sub
Resources
CREATE TABLE statement (Microsoft Access SQL)
How can I refresh c# dataGridView after update?
Getting binary data using SqlDataReader

Comparing TimeoftheDay to a String

Error in Comparing Time to a String
Cdate is my previous code and i revise it to compareTime Can anyone
help me if the current expression to compare time is correct because
the message is "Contact your Administrator! Maybe your not
registered."
So the expression is still "false"
#Region "TIMER"
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
LBLDATE.Text = My.Computer.Clock.LocalTime.Date
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LBLTIME.Text = TimeOfDay
End Sub
#End Region
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
Dim A As Integer
Dim result = Nothing
Dim compareTime As String = "7:01:00 PM"
' Dim amlate1 As String = "7:01:00 PM"
Dim remm1 As String
' If CDate(Form7TO3.LBLTIME.Text) >= CDate(amlate1) Then
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES LIKE '" & Form7TO3.txtinput.Text & "' AND SDATE = '" & Form7TO3.LBLDATE.Text & "'"
Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim DS As New DataSet
DA.Fill(DS, "dtrdb")
A = DS.Tables("dtrdb").Rows.Count
If A > 0 Then
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, AM_IN, FIRST_AM_REMARK, SDATE) VALUES (#MEM_CODES, #AM_IN, #FIRST_AM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form7TO3.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #AM_IN", Form7TO3.LBLTIME.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_AM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", DateTime.Parse(Form7TO3.LBLDATE.Text)))
conn.Open()
cmd.ExecuteNonQuery()
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
End Try
Return result
Here's my current codes
Can anyone revise this codes
If the record is already exist a messagebox will appear saying "Sorry you finished log in"
otherwise it will save/add records on my database
(The problem is , if the records still exists it add/insert another the same record)
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
'Dim A As Integer
Dim result = Nothing
'Dim time_1 As String = DateTime.Parse("11:00:00 PM").ToString("T")
'Dim time_2 As String = DateTime.Now.ToString("T")
Dim remm1 As String
Dim PMOUT As String = "11:00:00 PM"
Dim str As String = "HH:mm:ss"
str = TimeOfDay()
' If DateTime.Now.TimeOfDay > amlate1.TimeOfDay Then
' If DateTime.Compare(time_1, time_2) > 0 Then
If str >= PMOUT Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
conn.Open()
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES = '" & Form11TO7.txtinput.Text & "' AND SDATE = #" & FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate) & "#"
' Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim cmd1 As New OleDb.OleDbCommand(sql1, conn)
'Dim DS As New DataSet
'DA.Fill(DS, "dtrdb")
'A = DS.Tables("dtrdb").Rows.Count
'If A > 0 Then
Using reader As OleDb.OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'user already finished to time in
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, PM_IN, FIRST_PM_REMARK, SDATE) VALUES (#MEM_CODES, #PM_IN, #FIRST_PM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form11TO7.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #PM_IN", str))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_PM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate)))
Dim icount As String
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
End Using
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
'MessageBox.Show(ms = "Contact your Administrator! Maybe your not registered." & vbNewLine & ex.Message)
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
'MessageBox.Show(ex.Message)
End Try
Return result

odbc reader for csv in vb.net

I'm writing a program that should handle million of datasets in csv in a short time, my idea was to use odbc because of performance reasons, therefore i read all the data with odbc and save it in memory, thereafter i add parameters and insert it in sql db, here is my code so far:
Using connection As New OdbcConnection("jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};" & filePath & "Extensions=csv;Persist Security Info=False;")
Dim reader As OdbcDataReader
Dim i As Integer
Dim r As SeekZeilen
Dim TextFileTable As DataTable = Nothing
Dim line As String = reader.Read()
Me.ParseString(line)
Dim memStream As New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
r.erste_Zeile = TextFileReader.ReadFields()
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
For i = 0 To r.erste_Zeile.Length - 1
Dim Column As New DataColumn(r.erste_Zeile(i))
Column.ReadOnly = True
TextFileTable.Columns.Add(Column)
Next
End If
DataGridView1.DataSource = TextFileTable
End Using
While reader.HasRows
line = reader.Read()
Me.ParseString(line)
memStream = New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
DataGridView1.DataSource = TextFileTable
Try
r._Rest = TextFileReader.ReadFields()
ReplaceChars(r._Rest)
If Not r._Rest Is Nothing Then
Dim oSQL As New DBUmgebung.cdb.SQL()
oSQL.init()
AddParameters(oSQL, r)
oSQL.ausfuehrenSQL(DBUmgebung.cdb.KSQLCommand.INSERT, _table, "")
Dim dtRow As DataRow = TextFileTable.NewRow
For i = 0 To r._Rest.Length - 1
dtRow(i) = r._Rest(i).ToString()
Next
TextFileTable.Rows.Add(dtRow)
DataGridView1.Refresh()
Application.DoEvents()
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error! " & ex.Message & _
"")
Catch sqlEx As SqlException
MessageBox.Show(sqlEx.Message)
rtbSql.Focus()
Exit For
Catch ex As Exception
MessageBox.Show(ex.Message)
rtbSql.Focus()
Exit For
End Try
End Using
End While
reader.Close()
End Using
the problem is that i get null pointer exception for a unknown reason, does anyone have idea what i did wrong? is it probably because my odbc reader is not properly initialized?
Try this. This will read the csv file as all text into a datatable. Once in the Datatable you could then insert the records into SQL. You can always adjust this to handle multiple csv files.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable
Try
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
da.Fill(dt)
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function

Populating Datagrid

I am creating a pageant scoring system,
I have this functions for populating my datagridview's first column using query:
Public Sub searchContestant()
If comboCategory.SelectedIndex <> 0 Then
Dim id As Integer = Login.JudgeBindingSource1.Current("Cont_id")
Dim critID As Integer = Convert.ToInt32(lblID.Text)
'search the contest record by the contest_id
Dim con As New SqlConnection
Dim reader As SqlDataReader
Dim reader2 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
Try
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & critID & "' ", con)
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
' Execute Query
reader = cmd.ExecuteReader()
nc.Name = "Contestants"
nc.Width = 250
nc.ReadOnly = True
DataGridView1.Columns.Add(nc)
While reader.Read()
nc = New DataGridViewTextBoxColumn
nc.Name = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.HeaderText = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.Width = 150
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
Try
'populate contestant rows
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
reader2 = cmd2.ExecuteReader()
While reader2.Read()
nc = New DataGridViewTextBoxColumn
nc.Width = 100
DataGridView1.Rows.Add(reader2.GetString(2).ToString())
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End If
End Sub
And for succeeding columns :
Public Sub searchCriteria()
Dim con As New SqlConnection
Dim reader4 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
Try
'populate Criteria
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & lblID.Text & "' ", con)
con.Open()
reader4 = cmd.ExecuteReader
While reader4.Read
nc = New DataGridViewTextBoxColumn
nc.Name = reader4.GetString(1).ToString & Chr(13) & reader4.GetString(2).ToString & "%"
nc.Width = 100
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End Sub
This is the output:
And everytime a judge login, I insert data into the system with this function:
Public Sub makeTransaction()
Dim con2 As New SqlConnection
'get the judge id upon logging in
Dim judgeID = Login.JudgeBindingSource1.Current("Judge_id")
'get the contest id of the judge
Me.JudgeTableAdapter.FillByJudgeID(Me.PSSDataSet.Judge, judgeID)
Dim JudgeContestid = Login.JudgeBindingSource1.Current("Cont_id")
Me.ContestantTableAdapter.FillByContestID(Me.PSSDataSet.Contestant, JudgeContestid)
'get the contestant id
Me.ContestTableAdapter.FillByContestID(Me.PSSDataSet.Contest, JudgeContestid)
Dim contestID As Integer = ContestBindingSource.Current("Cont_id")
'get the category of the contest
Me.CategoryTableAdapter.FillByContestID(Me.PSSDataSet.Category, Convert.ToInt32(contestID))
For Each Category As DataRow In Me.PSSDataSet.Category.Rows
Me.CriteriaTableAdapter.FillByCategoryID(Me.PSSDataSet.Criteria, Category("Cat_id"))
For Each Contestant As DataRow In Me.PSSDataSet.Contestant.Rows
For Each Criteria As DataRow In Me.PSSDataSet.Criteria.Rows
TransactionsTableAdapter.Insert(JudgeContestid, Contestant("Con_id"), Criteria("Cri_id"), 0)
Next
Next
Next
End Sub
Now my problem is, how can I populate the datagrid using the data recently made by MakeTransaction() function?

Syntax Error! >_<

Guy's Cant seem to find my error in VB.Net ! my codes are all right ! but the function still won't save on the database cause of Syntax error in my Insert into statement ! Please help me ! :D!
This is my Code!:D!
Dim Transaction As OleDb.OleDbTransaction = Nothing
Dim Connection As OleDb.OleDbConnection = Nothing
Try
Connection = New OleDb.OleDbConnection(My.Settings.POS_CanteenConnectionString)
Connection.Open()
Transaction = Connection.BeginTransaction
Dim SQL As String = "Insert into Recipt (ReciptDate,ReciptTotal)Values(:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = Connection
CMD1.Transaction = Transaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
SQL = "Select Max(ReciptID) As MAXID from Recipt"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = Connection
CMD2.Transaction = Transaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
Dim I As Integer
For I = 0 To DGV3.Rows.Count - 1
Dim BarCode As String = DGV3.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV3.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV3.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV3.Rows(I).Cells(4).Value
Dim CMD3 As New OleDb.OleDbCommand
SQL = "Insert to ReciptDetails" & _
"(ReciptID,BarCode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4 )"
CMD3.Connection = Connection
CMD3.Transaction = Transaction
CMD3.CommandText = SQL
CMD3.Parameters.AddWithValue(":0", ReciptID)
CMD3.Parameters.AddWithValue(":1", BarCode)
CMD3.Parameters.AddWithValue(":2", BuyPrice)
CMD3.Parameters.AddWithValue(":3", ItemCount)
CMD3.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
Transaction.Commit()
Transaction.Dispose()
Connection.Close()
Connection.Dispose()
DGV3.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Transaction IsNot Nothing Then
Transaction.Rollback()
End If
If Connection IsNot Nothing Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "ERROR")
End Try
Firstly, I don't think sp parameters are called by : prefix, you should use # instead. you'll therefore need to replace the .AddWithValue (everywhere) by;
CMD1.Parameters.AddWithValue("#0", Now.Date)
CMD1.Parameters.AddWithValue("#1", TextBox4.Text)
Secondly, I think the Insert syntax isn't right, you've place TO instead of INTO and space missing. Try this;
SQL = "Insert into ReciptDetails " & _
"(ReciptID, BarCode, ItemCount, ItemBuyPrice, ItemSellPrice)" & _
" Values (#0, #1, #2, #3, #4)"