Insert without duplicates MS Access using ASP.net (VB.net) - sql

I am building an e-commerce website as a school project. How can I make sure that I won't have duplicate users since this is the page where they have to fill in their user details.
This is the code I am using right now and the ExecuteNonquery doesn't work. It doesn't give any errors, it just skips it.
Protected Sub bntVerzenden_Click(sender As Object, e As EventArgs) Handles bntVerzenden.Click
Dim sqlCommand As String
Dim intGebruikersID, intRubriekID As Integer
Dim VerkopenConn As New OleDb.OleDbConnection
Dim VerkopenCommArtikel, VerkopenCommGebruiker, GebruikersIDComm, RubriekIDComm, EmailComm As New OleDb.OleDbCommand
VerkopenConn.ConnectionString = My.Settings.SvShopConnection
VerkopenCommArtikel.Connection = VerkopenConn
VerkopenCommGebruiker.Connection = VerkopenConn
GebruikersIDComm.Connection = VerkopenConn
RubriekIDComm.Connection = VerkopenConn
EmailComm.Connection = VerkopenConn
'Email Controleren
sqlCommand = "SELECT * FROM tblGebruiker WHERE GebruikersEmail = '" & txtEmail.Text & "'"
EmailComm.CommandText = sqlCommand
If VerkopenConn.State = ConnectionState.Closed Then VerkopenConn.Open()
If EmailComm.ExecuteNonQuery = 0 Then
'Gebruiker gegevens aan de database toevoegen
VerkopenCommGebruiker.CommandText = "INSERT INTO tblGebruiker (GebruikersNaam, GebruikersVoornaam, GebruikersEmail, GebruikersGSM) VALUES (#GebruikersNaam, #GebruikersVoornaam, #GebruikersEmail, #GebruikersGSM)"
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersNaam", txtNaam.Text)
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersVoornaam", txtVNaam.Text)
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersEmail", txtEmail.Text)
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersGSM", txtGsm.Text)
VerkopenCommGebruiker.ExecuteNonQuery()
'GebruikersID uit de database halen
GebruikersIDComm.CommandText = "SELECT tblGebruiker.GebruikersID FROM tblGebruiker WHERE tblGebruiker.GebruikersNaam = #Naam AND tblGebruiker.GebruikersVoornaam = #VNaam;"
GebruikersIDComm.Parameters.AddWithValue("#Naam", txtNaam.Text)
GebruikersIDComm.Parameters.AddWithValue("#VNaam", txtVNaam.Text)
intGebruikersID = Integer.Parse(GebruikersIDComm.ExecuteScalar)
'RubriekID uit de database halen
RubriekIDComm.CommandText = "SELECT tblRubriek.RubriekID FROM tblRubriek WHERE tblRubriek.RubriekNaam = #RubriekNaam"
RubriekIDComm.Parameters.AddWithValue("#RubriekNaam", lstRubriek.SelectedItem.ToString)
intRubriekID = Integer.Parse(RubriekIDComm.ExecuteScalar)
'Artikel gegevens aan de database toevoegen
VerkopenCommArtikel.CommandText = "INSERT INTO tblArtikel (ArtikelBeschrijving, ArtikelPrijs, RubriekID, ArtikelAankoopdatum, ArtikelTekoopgezet, ArtikelBeschikbaar, GebruikersID) VALUES ( #ArtikelBeschrijving, #ArtikelPrijs, #RubriekID, #ArtikelAankoopdatum, #ArtikelTekoopgezet, #ArtikelBeschikbaar, #GebruikersID)"
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelBeschrijving", txtArtikelBeschrijving.Text)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelPrijs", txtArtikelPrijs.Text)
VerkopenCommArtikel.Parameters.AddWithValue("#RubriekID", intRubriekID)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelAankoopdatum", CalAankoop.SelectedDate)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelTekoopgezet", calVerkoop.SelectedDate)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelBeschikbaar", True)
VerkopenCommArtikel.Parameters.AddWithValue("#GebruikersID", intGebruikersID)
VerkopenCommArtikel.ExecuteNonQuery()
VerkopenConn.Close()
Else
'GebruikersID uit de database halen
GebruikersIDComm.CommandText = "SELECT tblGebruiker.GebruikersID FROM tblGebruiker WHERE tblGebruiker.GebruikersNaam = #Naam AND tblGebruiker.GebruikersVoornaam = #VNaam;"
GebruikersIDComm.Parameters.AddWithValue("#Naam", txtNaam.Text)
GebruikersIDComm.Parameters.AddWithValue("#VNaam", txtVNaam.Text)
intGebruikersID = Integer.Parse(GebruikersIDComm.ExecuteScalar)
'RubriekID uit de database halen
RubriekIDComm.CommandText = "SELECT tblRubriek.RubriekID FROM tblRubriek WHERE tblRubriek.RubriekNaam = #RubriekNaam"
RubriekIDComm.Parameters.AddWithValue("#RubriekNaam", lstRubriek.SelectedItem.ToString)
intRubriekID = Integer.Parse(RubriekIDComm.ExecuteScalar)
'Artikel gegevens aan de database toevoegen
VerkopenCommArtikel.CommandText = "INSERT INTO tblArtikel (ArtikelBeschrijving, ArtikelPrijs, RubriekID, ArtikelAankoopdatum, ArtikelTekoopgezet, ArtikelBeschikbaar, GebruikersID) VALUES ( #ArtikelBeschrijving, #ArtikelPrijs, #RubriekID, #ArtikelAankoopdatum, #ArtikelTekoopgezet, #ArtikelBeschikbaar, #GebruikersID)"
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelBeschrijving", txtArtikelBeschrijving.Text)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelPrijs", txtArtikelPrijs.Text)
VerkopenCommArtikel.Parameters.AddWithValue("#RubriekID", intRubriekID)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelAankoopdatum", CalAankoop.SelectedDate)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelTekoopgezet", calVerkoop.SelectedDate)
VerkopenCommArtikel.Parameters.AddWithValue("#ArtikelBeschikbaar", True)
VerkopenCommArtikel.Parameters.AddWithValue("#GebruikersID", intGebruikersID)
VerkopenCommArtikel.ExecuteNonQuery()
VerkopenConn.Close()
End If
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">alert(""Jouw artikel staat nu te koop"")</SCRIPT>")
End Sub

You should hace some id field, like email or full name. You could create a unique index on this columna and catch the exception on insert. Or fire a first query to verify if the user is already added.

You can check whether the emailid that user provide is already exist in your database or not.Try this code:-
SqlConnection Conn=new SqlConnection(your_connectionstring);
SqlCommand command = new SqlCommand("select * from tblGebruiker where GebruikersEmail='" + emailid + "'", Conn);
DataTable dtl = new DataTable();
SqlDataAdapter sqlDA = new SqlDataAdapter(command);
sqlDA.Fill(dtl);
if (dtl.Rows.Count > 0)
{
Response.Write("<script>alert('User already registered')</script>");
}
else
{
VerkopenCommGebruiker.CommandText = "INSERT INTO tblGebruiker (GebruikersNaam, GebruikersVoornaam, GebruikersEmail, GebruikersGSM) VALUES (#GebruikersNaam, #GebruikersVoornaam, #GebruikersEmail, #GebruikersGSM)"
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersNaam", txtNaam.Text)
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersVoornaam", txtVNaam.Text)
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersEmail", txtEmail.Text)
VerkopenCommGebruiker.Parameters.AddWithValue("#GebruikersGSM", txtGsm.Text)
If VerkopenConn.State = ConnectionState.Closed Then VerkopenConn.Open()
VerkopenCommGebruiker.ExecuteNonQuery()
}

Related

Dynamic Sql - retrieve from Oracle

I have a form with button which should find records from Oracle database. I have three Textboxes on same form, and If text matches with values in fields of DB, Datagrid should show me this records. Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'connect to oracle DB
Dim oradb As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim SQL As String
SQL = "SELECT * FROM MyTable WHERE 1=1"
'SQL statement for 1st textbox
If Not TxtName.Text = "" Then
SQL = SQL & " AND USER_NAME =" & TxtName.Text
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text = "" Then
SQL = SQL & " AND USER_SURNAME =" & TxtSurname.Text
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text = "" Then
SQL = SQL & " AND USER_ADDRESS=" & TxtAddress.Text
End If
'select SQL statements and retrieve data using ExecuteReader
Dim cmd As New OracleCommand(SQL, conn)
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Sub
What am I doing wrong, nothing happens when button clicked?
This is a non-tested sample of the direction you could try:
Private Sub populateDataGridView()
'connect to oracle DB
Const connectionString As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Using conn As New OracleConnection(connectionString)
conn.Open()
Using cmd As New OracleCommand()
Dim SQL As String = "SELECT * FROM testtable "
Dim conjunction As String = " Where "
'SQL statement for 1st textbox
If Not TxtName.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " USER_NAME like :username")
cmd.Parameters.Add(New OracleParameter("username", String.Concat("%", TxtName.Text, "%")))
conjunction = " and "
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_surname like :usersurname")
cmd.Parameters.Add(New OracleParameter("usersurname", String.Concat("%", TxtSurname2.Text, "%")))
conjunction = " and "
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_address like :useraddress")
cmd.Parameters.Add(New OracleParameter("useraddress", String.Concat("%", TxtAddress.Text, "%")))
End If
'select SQL statements and retrieve data using ExecuteReader
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub

UPDATE statement in VB connecting to Access

I'm trying to update the position column in my access database but the problem is I'm having problem update that column while the rest of the column will not give out error message.
The error message: Syntax error in UPDATE statement, Microsoft JET database engine...
The code:
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As New DataSet
Dim da As OleDbDataAdapter
Dim MaxRows As Integer
Dim i As Integer
Dim sql As String
Private Sub updateButton_Click(sender As Object, e As EventArgs) Handles updateButton.Click
Using myConnection = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\LecturerDetail.mdb")
myConnection.Open()
Dim str As String
str = "UPDATE lecturer " & _
"SET [empName] = ?,[empId] = ?, [position] =?, [faculty] = ? " & _
" , [degree1] = ?, [degree2] = ?, [degree3] = ?,[degree] = ?, [empType] = ? " & _
" ,[icNo] = ?, [citizenship] = ?, [phoneNo] = ?, [email] = ?,[permitNo] = ? " & _
" , [permitStartDate] = ?, [permitEndDate] = ?, [pStatus] =?, [remark] =? " & _
" WHERE ([empId] = ?) "
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#empName", nameTxt.Text)
cmd.Parameters.AddWithValue("#empId", empIdTxt.Text)
cmd.Parameters.AddWithValue("#position", positionComboBox.SelectedText)
cmd.Parameters.AddWithValue("#faculty", facultyComboBox.SelectedText)
cmd.Parameters.AddWithValue("#degree1", empDeg1.Text)
cmd.Parameters.AddWithValue("#degree2", empDeg2.Text)
cmd.Parameters.AddWithValue("#degree3", empDeg3.Text)
cmd.Parameters.AddWithValue("#degree", empDeg4.Text)
cmd.Parameters.AddWithValue("#empType", empTypeComboBox.SelectedText)
cmd.Parameters.AddWithValue("#icNo", icTxt.Text)
cmd.Parameters.AddWithValue("#citizenship", citizenshipComboBox.SelectedText)
cmd.Parameters.AddWithValue("#phoneNo", phoneTxt.Text)
cmd.Parameters.AddWithValue("#email", emailTxt.Text)
cmd.Parameters.AddWithValue("#permitNo", permitNoTxt.Text)
cmd.Parameters.AddWithValue("#permitStartDate", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#permitEndDate", DateTimePicker2.Text)
cmd.Parameters.AddWithValue("#pStatus", statusComboBox.Text)
cmd.Parameters.AddWithValue("#remark", remark.Text)
cmd.Parameters.AddWithValue("#empId", empIdTxt.Text)
Try
cmd.ExecuteNonQuery()
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("lecturer").Rows(i).Item(0) = empIdTxt.Text
ds.Tables("lecturer").Rows(i).Item(1) = nameTxt.Text
ds.Tables("lecturer").Rows(i).Item(2) = positionComboBox.Text
ds.Tables("lecturer").Rows(i).Item(3) = facultyComboBox.Text
ds.Tables("lecturer").Rows(i).Item(4) = empDeg1.Text
ds.Tables("lecturer").Rows(i).Item(5) = empDeg2.Text
ds.Tables("lecturer").Rows(i).Item(6) = empDeg3.Text
ds.Tables("lecturer").Rows(i).Item(7) = empDeg4.Text
ds.Tables("lecturer").Rows(i).Item(8) = empTypeComboBox.Text
ds.Tables("lecturer").Rows(i).Item(9) = icTxt.Text
ds.Tables("lecturer").Rows(i).Item(10) = citizenshipComboBox.Text
ds.Tables("lecturer").Rows(i).Item(11) = phoneTxt.Text
ds.Tables("lecturer").Rows(i).Item(12) = emailTxt.Text
ds.Tables("lecturer").Rows(i).Item(13) = permitNoTxt.Text
ds.Tables("lecturer").Rows(i).Item(14) = DateTimePicker1.Value
ds.Tables("lecturer").Rows(i).Item(15) = DateTimePicker2.Value
ds.Tables("lecturer").Rows(i).Item(16) = statusComboBox.Text
ds.Tables("lecturer").Rows(i).Item(17) = remark.Text
da.Update(ds, "lecturer")
ds.AcceptChanges()
myConnection.Close()
MsgBox("Record Updated")
Catch ex As Exception
MessageBox.Show(ex.Message & "-" & ex.Source)
End Try
End Using
End Sub
My code is to update the columns and allow user to navigate to the next record.
I'm new to visual basic so detail description and guidance are appreciated. Thanks. In addition, i'm trying to create auto notification system based on the dates. Anyone might enlighten me on which methods or applications to be used in visual basic to do it.
No need to create the update query hand. The CommandBuilder itself generate the necessary instructions to update the database.
Dim ds As New DataSet
Dim da As OleDbDataAdapter
Dim MaxRows As Integer
Dim i As Integer
Dim sql As String
Private Sub updateButton_Click(sender As Object, e As EventArgs) Handles updateButton.Click
Using myConnection = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\LecturerDetail.mdb")
myConnection.Open()
Dim str As String
str = "SELECT * FROM lecturer WHERE ([empId] = #empId)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#empId", empIdTxt.Text)
Try
da = new OleDbDataAdapter(cmd)
da.Fill(ds,"lecturer")
ds.Tables("lecturer").Rows(i).Item(0) = empIdTxt.Text
ds.Tables("lecturer").Rows(i).Item(1) = nameTxt.Text
ds.Tables("lecturer").Rows(i).Item(2) = positionComboBox.Text
ds.Tables("lecturer").Rows(i).Item(3) = facultyComboBox.Text
ds.Tables("lecturer").Rows(i).Item(4) = empDeg1.Text
ds.Tables("lecturer").Rows(i).Item(5) = empDeg2.Text
ds.Tables("lecturer").Rows(i).Item(6) = empDeg3.Text
ds.Tables("lecturer").Rows(i).Item(7) = empDeg4.Text
ds.Tables("lecturer").Rows(i).Item(8) = empTypeComboBox.Text
ds.Tables("lecturer").Rows(i).Item(9) = icTxt.Text
ds.Tables("lecturer").Rows(i).Item(10) = citizenshipComboBox.Text
ds.Tables("lecturer").Rows(i).Item(11) = phoneTxt.Text
ds.Tables("lecturer").Rows(i).Item(12) = emailTxt.Text
ds.Tables("lecturer").Rows(i).Item(13) = permitNoTxt.Text
ds.Tables("lecturer").Rows(i).Item(14) = DateTimePicker1.Value
ds.Tables("lecturer").Rows(i).Item(15) = DateTimePicker2.Value
ds.Tables("lecturer").Rows(i).Item(16) = statusComboBox.Text
ds.Tables("lecturer").Rows(i).Item(17) = remark.Text
Dim cb As New OleDb.OleDbCommandBuilder(da)
da.Update(ds, "lecturer")
ds.AcceptChanges()
myConnection.Close()
MsgBox("Record Updated")
Catch ex As Exception
MessageBox.Show(ex.Message & "-" & ex.Source)
End Try
End Using
End Sub

DataReader Error VB.net and mySql

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim reader As MySqlDataReader
Dim query As String
Dim md As String
md = Me.mskmembdate.Text
md = Me.bday.Text
md = Me.spsbday.Text
Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
query = "SELECT * FROM member WHERE (memor = '" & membor.Text & "')"
sqlcom = New MySqlCommand(query, conn)
reader = sqlcom.ExecuteReader
While reader.Read()
Me.lblmembname.Text = reader("membname").ToString
Me.membtype.Text = reader("membtype").ToString
Me.mskmembdate.Text = CDate(reader("membdate")).ToString("MMddyyyy")
Me.lname.Text = reader("lname").ToString
Me.fname.Text = reader("fname").ToString
Me.mname.Text = reader("mname").ToString
Me.nameex.Text = reader("nameex").ToString
Me.bday.Text = CDate(reader("bday")).ToString("MMddyyyy")
Me.membtype.Text = reader("membtype").ToString
Me.spslname.Text = reader("spslname").ToString
Me.spsfname.Text = reader("spsfname").ToString
Me.spsmname.Text = reader("spsmname").ToString
Me.spsbday.Text = CDate(reader("spsbday")).ToString("MMddyyyy")
Me.civil.Text = reader("civil").ToString
Me.sex.Text = reader("sex").ToString
Me.municipal.Text = reader("municipal").ToString
Me.brgy.Text = reader("brgy").ToString
Me.purok.Text = reader("purok").ToString
Me.district.Text = reader("district").ToString
Me.certno.Text = reader("certnumb").ToString
Me.resno.Text = reader("resonumb").ToString
Me.cpno.Text = reader("cpno").ToString
Me.recstat.Text = reader("recstat").ToString
End While
reader.Close()
conn.Dispose()
Catch ex As Exception
End Try
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim dr As OleDbDataReader
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "D:\N.A.C. JR\SAMPLE VB 2008\NewMembership\NewMembership\bin\Debug\profilepic.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM info WHERE (memor = '" & membor.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader()
While dr.Read()
orspspic.Text = dr("spspicture").ToString
orpic.Text = dr("picture").ToString
End While
dr.Close()
myConnection.Close()
varimage = orpic.Text
varimage = orspspic.Text
pic.ImageLocation = orpic.Text
spspic.ImageLocation = orspspic.Text
End Sub
This is my code from frmload i click listview data then form2 opens and sets the data into text boxes but this error pops out "There is already an open DataReader associated with this Connection which must be closed first" ? How can i solve it . Any ideas how to solve this kind of problem?

Load SQL Statement for Dataset From SqlServer

I have a code that will fill the dataset for my crystal report which was written down as follows:
Dim str1 As String = "SELECT * FROM farm_loan WHERE id = '" & txtAgreement.Text & "'"
Dim str2 As String = "SELECT * FROM cd_farmers WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str3 As String = "SELECT * FROM cd_Address WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str4 As String = "SELECT * FROM cd_loan_charges WHERE loanid = '" & txtAgreement.Text & "'"
Dim ad1 As SqlDataAdapter = New SqlDataAdapter(str1, Conn)
Dim ad2 As SqlDataAdapter = New SqlDataAdapter(str2, Conn)
Dim ad3 As SqlDataAdapter = New SqlDataAdapter(str3, Conn)
Dim ad4 As SqlDataAdapter = New SqlDataAdapter(str4, Conn)
Dim LDPSDataSet As DataSet = New DataSet()
ad1.Fill(LDPSDataSet, "farm_loan")
ad2.Fill(LDPSDataSet, "cd_farmers")
ad3.Fill(LDPSDataSet, "cd_Address")
ad4.Fill(LDPSDataSet, "cd_loan_charges")
The above code works fine. What I am trying to do is to store the sql statement in one table called tblDataSet and load the same from sql server. Here are my code.
cmd = New SqlCommand("SELECT * FROM tblDataSet WHERE Flag = 'Y'", Conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ad As SqlDataAdapter
If reader.HasRows Then
Do While reader.Read()
MySql = reader(1).ToString
Dim table As String = reader(2).ToString
Dim comm As SqlCommand = New SqlCommand(MySql)
comm.Connection = Conn
comm.CommandType = CommandType.Text
comm.Parameters.Add("#AgreementID", SqlDbType.Int).Value=txtAgreement.Text
comm.Parameters.Add("#CustomerID", SqlDbType.Int).Value = txtCustID.Text
Dim ad As SqlDataAdapter = New SqlDataAdapter
For Each tbl As DataTable In LDPSDataSet.Tables()
If tbl.TableName = table Then
ad.SelectCommand = comm
End If
Exit For
ad.Update(tbl)
Next
Loop
End If
I have not encountered any error but no value is fetch to the crystal report.
My code in to fetch data to crystal report is show below.
With mReport
repOptions = .PrintOptions
With repOptions
.PaperOrientation = rptOrientation
.PaperSize = rptSize
.PrinterName = printer
End With
.Load(rptPath, OpenReportMethod.OpenReportByDefault)
.SetDataSource(LDPSDataSet)
'.Refresh()
.PrintToPrinter(1, True, 0, 0)
End With
Please help me identify the problem with my code.
Thanks in advance.

How do I catch an SQL exception in a VB.NET 2010 code?

Okay, I am building a VB.NET system but I'm having troubles in catching an SQL exception in some parts of my code. In short, I am using a SELECT sql query to retrieve a particular record and I want to determine whether a record exist in a MSAccess database so that I don't retrieve 0 rows. 0 rows will lead to an exception during printing to a TextField. The following is a sample code I'm working on:
If txSearch.Text = "" Then
MsgBox("Please type the user id or use the barcode reader to scan", MsgBoxStyle.OkOnly, "Search Field Empty")
End If
'ElseIf txSearch.Text != "" Then
If txSearch.Text <> "" Then
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim dt As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim de As OleDb.OleDbDataAdapter
Dim sql As String
Dim sql1 As String
Dim temp_num As Integer
Dim cmd As New OleDb.OleDbCommand
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = new.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim search As String
search = txSearch.Text
MessageBox.Show("You are going to search for " + search + ". Click OK to continue.")
sql = "SELECT * FROM Student_Details WHERE Admin_No = '" & txSearch.Text & "'"
sql1 = "SELECT * FROM Laptop_Details WHERE Admin_No = '" & txSearch.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
de = New OleDb.OleDbDataAdapter(sql1, con)
'Dim check As Integer = sql.
'If check > 0 Then
'da.SelectCommand = cmd
ds = New DataSet("Student_Details")
da.Fill(ds, "Student_Details")
dt = New DataSet("Laptop_Details")
de.Fill(dt, "Laptop_Details")
'con.Close()
'If sql <> "" And sql1 <> "" Then
'If ds.Equals(1) And ds.Equals(1) Then
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
Dim com As New OleDb.OleDbCommand(sql, con)
Dim com1 As New OleDb.OleDbCommand(sql1, con)
Try
temp_num = com.ExecuteNonQuery
temp_num = com1.ExecuteNonQuery
Catch ex As IndexOutOfRangeException
Trace.WriteLine(ex.ToString)
End Try
con.Close()
'End If
'End If
End If
Try something like this:
if ds.Tables("Student_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
End if
if ds.Tables("Laptop_Details").Rows.Count > 0
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
End if
To help you with your comment I would do it like that:
if ds.Tables("Student_Details").Rows.Count > 0 And ds.Tables("Laptop_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
else
MsgBox("The user with id "+txSearch.Text+" does not exist")
end if
Try to use try-catch statement:
Try
Your code here for your query statements.
Catch ex as Exception MsgBox(ex.Message)End Try