retrieving an autonumumber primary key field - vb.net

I've this function to retrieve employee details in my Employees table. I am using vb.net 2012 and MS Access for my database. My problem is how to retrieve employee details using their ID's with an autonumber and primary key attributes/datatype? here's my code:
Public Sub DisplayEmployeeDetail()
Try
sqlEmployeeInfo = "SELECT * FROM tblEmployees WHERE tblEmployees.ID = " + txtDTRidnum.Text + ";"
Dim da As OleDb.OleDbDataAdapter = New OleDbDataAdapter(sqlEmployeeInfo, con)
Dim ds As New DataSet
da.Fill(ds, "tblEmployees")
Dim temp = ds.Tables("tblEmployees").Rows.Count
For i = 0 To temp - 1
lblFname.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("FirstName"))
lblLname.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("LastName"))
lblMname.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("MiddleName"))
lblAddress.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("Address"))
lblPosition.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("Position"))
Next
Catch ex As Exception
MessageBox.Show("Error in load: " & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
it gives System.Data.OleDb.Exception: Syntax error (missing operator) in query expression 'tblEmployees.ID='

use single quotes like this:
sqlEmployeeInfo = "SELECT * FROM tblEmployees WHERE tblEmployees.ID = '" + txtDTRidnum.Text + "';"
Additional you can try this even you don't want to use:
Private Sub getData()
Dim empDA As OleDbDataAdapter = New OleDbDataAdapter()
Dim empDS As DataSet = New DataSet
Dim empTable As DataTable = New DataTable("EMPLOYEES")
Dim adoConn As ADODB.Connection = New ADODB.Connection()
Dim adoRS As ADODB.Recordset = New ADODB.Recordset()
Try
empTable.Columns.Add("FirstName", Type.GetType("System.String"))
empTable.Columns.Add("LastName", Type.GetType("System.String"))
empTable.Columns.Add("MiddleName", Type.GetType("System.String"))
empTable.Columns.Add("Address", Type.GetType("System.String"))
empTable.Columns.Add("Position", Type.GetType("System.String"))
empDS.Tables.Add(empTable)
'Use ADO objects from ADO library (msado15.dll) imported
' as .NET library ADODB.dll using TlbImp.exe
'Specify your connection string here
adoConn.Open("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;", "", "", -1)
adoRS.Open("SELECT * FROM tblEmployees WHERE tblEmployees.ID = " + txtDTRidnum.Text + ";", adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1)
empDA.Fill(empTable, adoRS)
Dim temp = empTable.Rows.Count
For i = 0 To temp - 1
lblFname.Text = CStr(empTable.Rows(i).Item("FirstName"))
lblLname.Text = CStr(empTable.Rows(i).Item("LastName"))
lblMname.Text = CStr(empTable.Rows(i).Item("MiddleName"))
lblAddress.Text = CStr(empTable.Rows(i).Item("Address"))
lblPosition.Text = CStr(empTable.Rows(i).Item("Position"))
Next
adoRS.Close()
adoConn.Close()
Catch ex As Exception
MessageBox.Show("Error in load: " & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
adoRS.Close()
adoConn.Close()
End Try
End Sub
This Example Here

This error occurs because the text field txtDTRidnum.Text is empty.

Related

attempetd to dived by zero print crystal reports

I Have one Project in VB.net i Print Barcode Label, But I have one Problem I can't Solve, When I show Reports In ReportViewer work FINE but when i try to PRINT display this ERROR "attempted to divide by zero" "Crystal Report Windows Form Viewer"
I don't have any formula in Report just Parameters!
Try
If listView1.CheckedItems.Count > 0 Then
Dim Condition As String = ""
Dim Condition1 As String = ""
For I = 0 To listView1.CheckedItems.Count - 1
Condition += String.Format("'{0}',", listView1.CheckedItems(I).Text)
Condition1 += String.Format("'{0}',", listView1.CheckedItems(I).SubItems(3).Text)
Next
Condition = Condition.Substring(0, Condition.Length - 1)
Condition1 = Condition1.Substring(0, Condition1.Length - 1)
Cursor = Cursors.WaitCursor
Timer1.Enabled = True
con = New SqlConnection(cs)
con.Open()
Dim st As String = "Select Barcode,Productname,(SalesPrice) as SalesRate from Product where ProductCode in (" & Condition & ") "
For j As Integer = 1 To Int32.Parse(Val(txtNoOfCopies.Text)) - 1
st = st & "Union all Select Barcode,Productname,(SalesPrice) as SalesRate from Product where ProductCode in (" & Condition & ")"
Next
cmd = New SqlCommand(st, con)
adp = New SqlDataAdapter(cmd)
dtable = New DataTable()
adp.Fill(dtable)
con.Close()
ds = New DataSet()
ds.Tables.Add(dtable)
ds.WriteXmlSchema("BarcodeLabelPrinting1.xml")
Dim rpt As New rptBarcodeLabelPrinting1
rpt.SetDataSource(ds)
rpt.SetParameterValue("p1", txtCompany.Text)
rpt.SetParameterValue("p2", txtCurrencyCode.Text)
frmReport.CrystalReportViewer1.ReportSource = rpt
frmReport.ShowDialog()
rpt.Close()
rpt.Dispose()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try

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

Displaying multiple records

Private Sub Line_Change2()
Dim cn As New SqlClient.SqlConnection("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select Id,Payroll_Id,ProductCode,Description,Qty from dbo.SmLine where Payroll_Id ='" + Txt1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("Id")
Cmb1.Text = reader.Item("ProductCode")
Des1.Text = reader.Item("Description")
Qty1.Text = reader.Item("Qty")
TextBox2.Text = reader.Item("Id")
Cmb2.Text = reader.Item("ProductCode")
Des2.Text = reader.Item("Description")
Qty2.Text = reader.Item("Qty")
TextBox3.Text = reader.Item("Id")
Cmb3.Text = reader.Item("ProductCode")
Des3.Text = reader.Item("Description")
Qty3.Text = reader.Item("Qty")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I am new to vb coding just want to help with displaying multiple rows on multiple textboxes. Above code picks up Payroll Id from a textbox from another table and then it goes through dbo.Smline table below. I want to display the multiple records under the same payroll Id in different textboxes. This code doesn't seem to be working properly.
On your form you have three set of controls. Thus, you are able to display just up to three products for each clicked Payroll_id. Your code inserts the same value in all sets. Change your code to the following:
Private Sub Line_Change2()
ResetControls()
Dim cn As New SqlClient.SqlConnection("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
Using cn
cn.Open()
Dim cmd As New SqlClient.SqlCommand
Dim reader As SqlClient.SqlDataReader
Try
Dim sql As String
sql = "select Id,Payroll_Id,ProductCode,Description,Qty from dbo.SmLine where Payroll_Id ='" + Txt1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim counter as Integer = 1
While reader.Read
CType(me.Controls.Find("TextBox" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Id").ToString()
CType(me.Controls.Find("Cmb" + CType(counter,String),False)(0),ComboBox).Text = reader.Item("ProductCode").ToString()
CType(me.Controls.Find("Des" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Description").ToString()
CType(me.Controls.Find("Qty" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Qty").ToString()
counter += 1
if counter =3 then Exit While
End While
reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Public Sub ResetControls()
For counter = 1 to 3
CType(me.Controls.Find("TextBox" + CType(counter,String),False)(0),TextBox).Text = ""
CType(me.Controls.Find("Cmb" + CType(counter,String),False)(0),ComboBox).Text = ""
CType(me.Controls.Find("Des" + CType(counter,String),False)(0),TextBox).Text = ""
CType(me.Controls.Find("Qty" + CType(counter,String),False)(0),TextBox).Text = ""
Next
End Sub
The above code exits the reading when it has more than three products for a Payroll_id, because you just have three sets of controls. But if you could have more than three products for each clicked Payroll_id and you want to display all of them, then you have to build your controls dynamically.

Am new to asp.net and vb.net.,now am trying to make a gridview of a database table

now am trying to make a gridview of a database table named UploadProject.while selecting row of gridview display image in seperate image field by using imageurl At the time of compiling of following code image not displayed.an error occured..."incorect syntax near '='".Any body please help me to solve this problem
Protected Sub OnSelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
lblimageid.Text = row.Cells(0).Text
lbltitle.Text = row.Cells(1).Text
get_Address()
get_Image()
End Sub
Public Sub get_Address()
Dim qry As String
Try
cn.Open()
qry = "select (title,imageurl) from [UploadProject] where [id] = '" & lblimageid.Text & "'"
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes2.ForeColor = Drawing.Color.Red
lblmes2.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub get_Image()
Dim qry As String
Try
cn.Open()
qry = "select title,imageurl from UploadProject where id = " & lblimageid.Text
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes1.ForeColor = Drawing.Color.Red
lblmes1.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub getProjectDT()
Dim qry As String
Try
qry = "select id,title,date from UploadProject "
sda = New SqlDataAdapter(qry, cn)
ds = New DataSet
sda.Fill(ds, "UploadProject")
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Catch ex As Exception
Finally
cn.Close()
End Try
End Sub

How do I Iterate Through DataTable and Decrypt a field?

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.