How to work with ListView1.SelectedItems().Text - vb.net

I am doing a project in vb.net and I've made a table with listview now the problem is that I am not be able to get a specific column item and only be able to get the item of first column (listview.selecteditems(0).text) and i.e. 0(zero)... ListView1.SelectedItems(1/2/3/so on).Text is not working.
My code is:
s = one_way.ListView1.SelectedItems(4).Text
cmd1 = New OleDbCommand("Select reference_no from Booking_Details", cn)
cmd1 = New OleDbCommand("insert into Booking_Details values(" & i & ",'" & one_way.ListView1.SelectedItems(0).Text & "','" & main.ComboBox1.Text & "','" & main.ComboBox9.Text & "','" & main.RadioButton2.Text & "','" & main.ComboBox2.Text & "','" & main.ComboBox4.Text & "','" & main.DateTimePicker2.Text & "','" & s & "',' ',' ','" & main.ComboBox5.Text & "','" & main.ComboBox6.Text & "','" & main.ComboBox7.Text & "')", cn)
cmd1.ExecuteNonQuery()
s = one_way.ListView1.SelectedItems(4).Text
cmd1 = New OleDbCommand("Select reference_no from Booking_Details", cn)
cmd1 = New OleDbCommand("insert into Booking_Details values('" & s & "')", cn)
cmd1.ExecuteNonQuery()
Someone please help.

In a listview, selecteditem(s) refers to the row. In order to add columns to it, you had to create and assign subitems and that is how you need to get the info back:
someInfo = listview.SelectedItems(X).SubItems(Z).Text
'SelectedItems(N).Text' is just returning the column 0 or item text.
your code is also ripe for a sql injection attack - you should use parameters: https://stackoverflow.com/a/16760887/1070452

Related

VB.NET 2010 Inserting data to table in access

PLease I need help whenever I register my form to database, it says registration successful but the last table (the TRANSACTION table) data information from my form does not input the info in my database only the table FORM and STUDENT have data from my form. Is there something wrong in my TRANSACTION code? or in database?
PLEASE HELP :((
sql = "INSERT INTO FORM VALUES ('" & txtformnum.Text & "' , '" & bcboRequest.Text & "' , '" & txtTotal.Text & "')"
da = New OleDb.OleDbDataAdapter(sql, con) '"
da.Fill(ds, "FORM")
sql = "INSERT INTO STUDENTS VALUES ('" & txtstudnum.Text & "','" & txtSurname.Text & "','" & txtGName.Text & "', '" & txtMName.Text & "', '" & txtAddress.Text & "', '" & status & "' , '" & txtYr.Text & "' , '" & cbostype.Text & "' , '" & chkClearance.Text & "', '" & txtCourse_Track.Text & "' , '" & txtCNumber.Text & "' , '" & dot.Value & "' , '" & dotdue.Value & "')"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "STUDENTS")
Dim sqlquery As String = "INSERT INTO TRANSACTION (Transaction_num,Stud_num,Form_num,Total Fee)" + "VALUES (" & txttransactionno.Text & ",'" & txtstudnum.Text & "'," & txtformnum.Text & "," & txtTotal.Text & ");"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
I don't know what database you're using, but if you're using MySQL or MS SQL Server then the keyword TRANSACTION is reserved and must be escaped to work within your statement.
If using MySQL, try changing your statement to INSERT INTO "TRANSACTION"
If using SQL Server, change your statement to INSERT INTO [TRANSACTION]
If you're not using either of those, post what database system you're using and I'll post the proper escape syntax.
Try changing this line
Dim sqlquery As String = "INSERT INTO TRANSACTION (Transaction_num,Stud_num,Form_num,Total Fee)" + "VALUES (" & txttransactionno.Text & ",'" & txtstudnum.Text & "'," & txtformnum.Text & "," & txtTotal.Text & ");"
To
Dim sqlquery As String = "INSERT INTO TRANSACTION ([Transaction_num],[Stud_num],[Form_num],[Total Fee]) " + "VALUES ('" & txttransactionno.Text & "','" & txtstudnum.Text & "','" & txtformnum.Text & "','" & txtTotal.Text & "');"
This should work fine.
Add the following to your code:
sqlcommand.ExecuteNonQuery()

incorrect syntax near 's' vb.net

I'm getting the error Incorrect syntax near 's'. Error appears after inputting data in SQL sometimes it doesn't appear but when same characters will input the error appears.
Error lined in the ExecuteNonQuery
conn = New SqlConnection(constr)
conn.Open()
comm = New SqlCommand("Insert into Admins(Firstname, Lastname, Birthday, Contact, Email, Address, Username, Password, SecurityQ1, SecurityQ2, SecurityI1, SecurityI2, SecurityA1, SecurityA2, Type) values ('" & BunifuMetroTextbox1.Text & "','" & BunifuMetroTextbox2.Text & "','" & BunifuDatepicker1.Value & "','" & BunifuMetroTextbox3.Text & "','" & BunifuMetroTextbox8.Text & "','" & BunifuMetroTextbox9.Text & "','" & BunifuMetroTextbox4.Text & "','" & BunifuMetroTextbox5.Text & "','" & BunifuDropdown1.selectedValue & "','" & BunifuDropdown2.selectedValue & "','" & BunifuDropdown1.selectedIndex & "','" & BunifuDropdown2.selectedIndex & "','" & BunifuMetroTextbox6.Text & "','" & BunifuMetroTextbox7.Text & "','" & admintype & "')", conn)
affector = comm.ExecuteNonQuery
conn.Close()

OleDbException was Unhandled: Syntax error in INSERT INTO statement

con.Open()
cmd.CommandText = "Insert Into tblEmp (FN,MN,LN,PAddHN,PAddSB,PAddMun,VPA,BD,BP,Tel,Rel,Cit,Height,Weight,Gend,SN,SOcc,NoC,AgeC,Stat,DS,FaN,FaOcc,MaN,MaOcc,PAdd,PTCN,PTCP,SSS,TIN,PHILH,PAGIBIG,CPNo,Sued,Age,BankAcc,empRfID,Principal,Department,Position,DRate,empID,OffT) Values('" & zfn & "','" & zmn & "','" & zln & "','" & zpaddhn & "','" & zpaddsb & "','" & zpaddmun & "','" & zvpa & "','" & zbd & "','" & zbp & "','" & ztel & "','" & zrel & "','" & zcit & "','" & zheight & "','" & zweight & "','" & zgend & "','" & zsn & "','" & zsocc & "','" & znoc & "','" & zagec & "','" & zstat & "','" & zds & "','" & zfan & "','" & zfaocc & "','" & zman & "','" & zmaocc & "','" & zpadd & "','" & zptcn & "','" & zptcp & "','" & zsss & "','" & ztin & "','" & zphilh & "','" & zpagibig & "','" & zcpno & "','" & zsued & "','" & zage & "','" & txtBankAcc.Text & "','" & zempRefID & "','" & cmbPrin.SelectedItem & "','" & cmbDept.SelectedItem & "','" & txtPos.Text & "','" & txtDRate.Text & "','" & empID & "','" & zOffTime & "')"
cmd.ExecuteNonQuery()
con.Close()
I got an error when running this in my program.. but when i paste the command in my ms access query and it runs successfully. is there any problem in my code? Pls help tnx.
where is your add parameter value?
You can try this
Try
con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dir\DB.accdb")
Dim command As String
command = "INSERT INTO Table (NOTIF, EMP_NO, EMP_NAME, [POSITION]) VALUES (#NOTIF, #EMP_NO, #EMP_NAME, #POSITION)"
con.Open()
Dim cmd As OleDbCommand
cmd = New OleDbCommand(command, con)
cmd.Parameters.AddWithValue("#NOTIF", NOTIFTextBox.Text)
cmd.Parameters.AddWithValue("#EMP_NO", EMP_NOTextBox.Text)
cmd.Parameters.AddWithValue("#EMP_NAME", EMP_NAMETextBox.Text)
cmd.Parameters.AddWithValue("#POSITION", POSITIONTextBox.Text)
cmd.ExecuteNonQuery()
Catch exceptionObject As Exception
MessageBox.Show(exceptionObject.Message)
Finally
con.Close()
End Try
this code i have used before, it work perfectly
Also your name of the field look like contain illegal value to VB.net, so must like this
[Height],[Weight],.... You can try to check it in you DATASET > Configure > Select Statement > Insert and you will look the illegal value.
Just like my POSITION field, it was illegal, so must contain "[]"
You may not use the "'", if the datatype is something like numbers. If i interprete it correctly, some of your fields are numbers.
con.Open()
cmd.CommandText = "Insert Into tblEmp (someInt, someString) VALUES (12, 'asdf')"
cmd.ExecuteNonQuery()
con.Close()
Beside this, you should get the same error in Acces, if you run you Query again. Use the debugger and add a Breakpoint at the "cmd.ExecuteNonQuery()" to get the finished query command string with all "'".

SQL injection in Visual Basic 2010

I don't know how to avoid SQL injection, could someone help me with my problem?
Here is my current code:
Private Function INSERT() As String
Dim SQLcon As New SqlConnection
Dim SQLdr As SqlDataReader
Try
SQLcon.ConnectionString = "Data Source=#####;Initial Catalog=OJT;Persist Security Info=True;User ID=####;Password=#####"
Dim SQLcmd As New SqlCommand("INSERT INTO dbo.Patients(pIDNo,pLName,pFName,pMI,pSex,pStatus,pTelNo,pDocID,pAddr,pStreet,pBarangay,pCity,pProvince,pLNameKIN,pFNameKIN,pMIKIN,pRelationKIN) VALUES('" & LabelPNumber.Text & "','" & txtLname.Text & "','" & txtFname.Text & "','" & txtMI.Text & "','" & txtPatientSex.Text & "','" & txtPatientSex.Text & "','" & txtPatientTelNo.Text & "','" & txtPatientDoctor.Text & "','" & txtStreetNumber.Text & "','" & txtStreetName.Text & "','" & txtBarangay.Text & "','" & txtCity.Text & "','" & txtProvince.Text & "','" & txtKinLname.Text & "','" & txtKinFname.Text & "','" & txtKinMI.Text & "','" & txtRelationToPatient.Text & "') ", SQLcon)
SQLcon.Open()
MsgBox("Patient Added!", MsgBoxStyle.Information)
SQLdr = SQLcmd.ExecuteReader()
Catch ex As Exception
MessageBox.Show("Error Occured, Can't Add Patient!" & ex.Message)
Finally
SQLcon.Close()
End Try
Return "done"
End Function
Basically anywhere you're concatenating strings together to create your SQL statement, especially that which comes from user input, is vulnerable.
Instead of doing this use SQL parameters, which can be added to the Parameters property of your SQL command (SQLcmd here).
I'll show you an example with one of your parameters - change your SQLCommand text to:
INSERT INTO dbo.Patients(pIDNo, ...)
VALUES(#pIDNo, ...)
Where #pIDNo is a "placeholder" in the string for the parameter value, which is sent separately from the command in the SQLParameters collection.
Then you can add a parameter with the same name as this "placeholder", and the value (it will derive the type from the value provided for you).
Here's the example from earlier:
SQLcmd.Parameters.AddWithValue("#pIDNo", LabelPNumber.Text)

how to store data from vb.net to access a database

I am using an Access database and vb.net 2010. I have created a table in the database with columns for title, datein, dateout and roomnymber. In vb.net 2010 I made a distinguished title = combobox, datein and dateout = DateTimePicker. When I click on F5, an error occurs: INSERT INTO Syntax Error in statement. Here's my code:
Dim sql As String
sql = "INSERT INTO tcekin(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" & "VALUES('" & ComboBox1.Text & _
"','" & txtFirstName.Text & "','" & txtLastName.Text & "','" & txtAddress.Text & "','" & cboCountry.Text & "','" & txtCompany.Text & "','" & txtNumber.Text & _
"','" & dptDateIn.Text & "','" & dptDateOut.Text & "','" & cboRoom.Text & "','" & txtNotes.Text & "')"
cmmd = New OleDbCommand(sql, cnn)
The first problem here is never NEVER NEVER use string concatenation to build your queries like that. Do it like this instead:
Dim sql As String = _
"INSERT INTO tcekin " &_
"(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" &_
"VALUES(?,?,?,?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.Parameters.AddWithValue("Title", Combobox1.Text)
cmmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
''# ...
''# ...
This will also make it easier to spot and avoid syntax errors like the one you're complaining about.