insert data to datagridview vb.net - vb.net

how do i insert money row and colomns to datagridview?
like i went to insert to datagridview this
is my code:
Private Sub btnSimpan_Click(sender As Object, e As EventArgs) Handles btnSimpan.Click
Call konek()
Dim simpan As String
Dim hasil As Integer
simpan = ("INSERT INTO T_Penjadwalan(Kode_Penjadwalan,Kelas,Kode_Jam,Jam_Mulai,Jam_Selesai,Senin,Selasa,Rabu,Kamis,Jumat,Sabtu) VALUES ('" & TBPENJADWALAN.Text & "','" & CBKelas.Text &
"','" & KJ1.Text & "','" & KJ2.Text & "','" & KJ3.Text & "','" & KJ4.Text & "','" & KJ5.Text & "','" & KJ6.Text & "','" & KJ7.Text & "','" & KJ8.Text & "','" & KJ9.Text &
"','" & JM1.Text & "','" & JM2.Text & "','" & JM3.Text & "','" & JM4.Text & "','" & JM5.Text & "','" & JM6.Text & "','" & JM7.Text & "','" & JM8.Text & "','" & JM9.Text &
"','" & JS1.Text & "','" & JS2.Text & "','" & JS3.Text & "','" & JS4.Text & "','" & JS5.Text & "','" & JS6.Text & "','" & JS7.Text & "','" & JS8.Text & "','" & JS9.Text &
"','" & Senin1.Text & "','" & Senin2.Text & "','" & Senin3.Text & "','" & Senin4.Text & "','" & Senin5.Text & "','" & Senin6.Text & "','" & Senin7.Text &
"','" & Selasa1.Text & "','" & Selasa2.Text & "','" & Selasa3.Text & "','" & Selasa4.Text & "','" & Selasa5.Text & "','" & Selasa6.Text & "','" & Selasa7.Text &
"','" & Rabu1.Text & "','" & Rabu2.Text & "','" & Rabu3.Text & "','" & Rabu4.Text & "','" & Rabu5.Text & "','" & Rabu6.Text & "','" & Rabu7.Text &
"','" & Kamis1.Text & "','" & Kamis2.Text & "','" & Kamis3.Text & "','" & Kamis4.Text & "','" & Kamis5.Text & "','" & Kamis6.Text & "','" & Kamis7.Text &
"','" & Jumat1.Text & "','" & Jumat2.Text & "','" & Jumat3.Text & "','" & Jumat4.Text & "','" & Jumat5.Text & "','" & Jumat6.Text & "','" & Jumat7.Text &
"','" & Sabtu1.Text & "','" & Sabtu2.Text & "','" & Sabtu3.Text & "','" & Sabtu4.Text & "','" & Sabtu5.Text & "','" & Sabtu6.Text & "','" & Sabtu7.Text & "')")
Try
cmd = New SqlCommand(simpan, conn)
hasil = cmd.ExecuteNonQuery()
If hasil > 0 Then
MessageBox.Show("Data Tersimpan", "Sukses", MessageBoxButtons.OK, MessageBoxIcon.Information)
Call tampilgridpenjadwalan()
End If
Catch ex As Exception
MessageBox.Show("Failed : " & ex.Message, "Gagal", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub}

First of all, as others have said, it is better to use parameters when executing SQL queries in VB.NET. It has many benefits and it's fairly simple.
Taking a snippet of your insert query as an example, instead of defining the first value clause as '" & TBPENJADWALAN.Text & "' the first value might be #TBPENJADWALAN.
The string from TBPENJADWALAN.Text is then passed to #TBPENJADWALAN using the following code:
cmd.Parameters.Add("#TBPENJADWALAN", OleDbType.VarChar, 50).Value = TBPENJADWALAN.Text
OleDbType.VarChar = Type of data you're storing
50 = Size of your field
So instead of your code as follows...
simpan = ("INSERT INTO T_Penjadwalan(Kode_Penjadwalan) VALUES ('" & TBPENJADWALAN.Text & "')
...it would be:
simpan = ("INSERT INTO T_Penjadwalan(Kode_Penjadwalan) VALUES (#TBPENJADWALAN)")
cmd.Parameters.Add("#TBPENJADWALAN", OleDbType.VarChar, 50).Value = TBPENJADWALAN.Text
It's much cleaner and more secure. You can take that example and change the rest of your insert query.
In terms of your original question about inserting data to a DataGridView, in my experience, it's best to create a DataSet and Adapter to fill it. Try this:
Dim adapter As SQLDataAdapter
Dim ds As New DataSet
adapter = New SQLDataAdapter(simpan, cmd)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)

Related

ACCESS Insert Into issue , unable to update lot of values at once

CurrentDb.Execute "INSERT INTO Data ([Region],[Office],[Employee Name],[Role],[Email ID],[T1 - New File Creation],[T1 - Roll forward],[T1 - Final package (PDF)],[T1 - Final package (paper)],[T1 - Efiling],[T1 - paper filing],[T1 - pre-season package (PDF)],[T1 -pre-season package (paper)],[T1 -FROR Checklist DESC Service check],[T1 - DT1 Intake and Initiate],[T1 - Scan and validate],[T1 - CRA website document downloads (Pulling NOA and other tax)],[T2 -New file creation],[T2 -Roll forward],[T2 -Final package (PDF)],[T2 -Final package (paper)],[T2 -Efiling],[T2 - Returns],[T3 - New file creation],[T3 - Roll forward],[T3 -Final package (PDF)],[T3 -Final package (paper)],[T3 - Net filing],[T3 -Paper filing])" & _
"VALUES ('" & Me.Region.Value & "','" & Me.Office.Value & "','" & Me.Employee_Name.Value & "','" & Me.Role.Value & "', '" & Me.Email_ID.Value & "','" & Me.T1___New_File_Creation.Value & "','" & Me.T1___Roll_forward.Value & "','" & Me.T1___Final_package__PDF_.Value & "','" & Me.T1___Final_package__paper_.Value & "','" & Me.T1___Efiling.Value & "','" & Me.T1___paper_filing.Value & "','" & Me.T1___pre_season_package__PDF_.Value & "','" & Me.T1__FROR_Checklist_DESC_Service_check.Value & "','" & Me.T1___DT1_Intake_and_Initiate.Value & "','" & Me.T1___Scan_and_validate.Value & "','" & Me.T1___CRA_website_document_downloads__Pulling_NOA_and_other_tax_.Value & "','" & Me.T1___CRA_website_document_downloads__Pulling_NOA_and_other_tax_.Value & "','" & Me.T2__New_file_creation & " ','" & Me.T2__Roll_forward & "','" & Me.T2__Final_package__PDF_ & "','" & Me.T2__Final_package__paper_ & "','" & Me.T2__Efiling & "','" & Me.T2___Returns & "'", & _
'" & Me.T3___New_file_creation & "','" & Me.T3___Roll_forward & "','" & Me.T3__Final_package__PDF_ & "','" & Me.T3__Final_package__paper_ & "','" & Me.T3___Net_filing & "','" & Me.T3__Paper_filing & "') ;"
CurrentDb.Execute "INSERT Into Data ([T3 - New file creation],[T3 - Roll forward],[T3 -Final package (PDF)],[T3 -Final package (paper)],[T3 - Net filing],[T3 -Paper filing])" & _
"Values ('" & Me.T3___New_file_creation & "','" & Me.T3___Roll_forward & "','" & Me.T3__Final_package__PDF_ & "','" & Me.T3__Final_package__paper_ & "','" & Me.T3___Net_filing & "','" & Me.T3__Paper_filing & "') & "
CurrentDb.Execute "INSERT INTO Data ([T4_T5 - New file creation],[T4_T5 - Roll forward],[T4_T5 - Final package (PDF)],[T4_T5 -Final package (paper)],[T4_T5 - Netfiling],[T4_T5 - Paper filing])" & _
"Values ('" & Me.T4_T5___New_file_creation & "','" & Me.T4_T5___Roll_forward & "','" & Me.T4_T5___Final_package__PDF_ & "','" & Me.T4_T5__Final_package__paper_ & "','" & Me.T4_T5___Paper_filing & "') & "
CurrentDb.Execute "Insert Into Data ([T3010 - New file creation],[T3010 -Roll forward],[T3010 - Final package (PDF)],[T3010 - Final package (paper)],[T3010 - Paper filing])" & _
"Values ('" & Me.T3010___New_file_creation & "','" & Me.T3010__Roll_forward & "','" & Me.T3010___Final_package__PDF_ & "','" & Me.T3010___Final_package__paper_ & "','" & Me.T3010___Paper_filing & "') & "
CurrentDb.Execute "Insert Into Data ([US tax -Letters(templafy & ms word)],[US tax -Printing/assembly(Dti)],[US tax - Printing/assembly(PDF)],[US tax - Printing/assembly(paper)],[Us tax - Paper filing]) " & _
"Values ('" & Me.US_tax__Letters_templafy___ms_word_ & "','" & Me.US_tax__Printing_assembly_Dti_ & "','" & Me.US_tax___Printing_assembly_PDF_ & "','" & Me.US_tax____Printing_assembly_paper_ & "','" & Me.Us_tax___Paper_filing & "') & "
CurrentDb.Execute "Insert Into Data ([USPT returns -Scan client information to pdf],[USPT returns -Printing/Assembly (CCH Axcess)],[USPT returns- Printing/Assembly (paper)],[USPT returns -Efiling],[USPT returns -Paper filing])" & _
"Values ('" & Me.USPT_returns__Scan_client_information_to_pdf & "','" & Me.USPT_returns__Printing_Assembly__CCH_Axcess_ & "','" & Me.USPT_returns__Printing_Assembly__paper_ & "','" & Me.USPT_returns__Efiling & "','" & Me.USPT_returns__Paper_filing & "') & "
CurrentDb.Execute "Insert Into Data ([GES tax - Finalize and mail],[GES tax - Finalize and pdf],[GES tax - Scanning],[O&E submissions],[EL Draft],[EL Finalize])" & _
"Values ('" & Me.GES_tax___Finalize_and_mail & "','" & Me.GES_tax___Finalize_and_pdf & "','" & Me.GES_tax___Scanning & "','" & Me.O_E_submissions & "','" & Me.EL_Draft & "','" & Me.EL_Finalize & "') & "
When I tried creating only one CurrentDB.Execute to update values it is not happening. When I created multiple currentdb.execute it is only working for the firstone.
Can anyone please modify the currentdb code and help me out.
Insert a DoEvents command before each CurrentDb.Execute or, better, use DAO and the power of Access and open Data as a DAO.Recordset.
Then use methods .AddNew and .Update to insert the seven sets of values - it will run way faster and with much cleaner code than the multiple calls for CurrentDb.Execute and the SQL concatenating.

"Error converting data type varchar to numeric" when I export data from Excel to SQL Server using VBA

I have created a macro in Excel to import and export data from SQL Server. However, when I try to export data, it throws an error
[Microsoft][ODBC SQL Server Driver][SQL Server]
Error converting data type varchar to numeric
The code worked fine when I was exporting integer numbers. The error came up when I tried exporting real numbers.
Dim gil, gibnr, gul, fil, fibnr, ful, qil, qibnr, qul, xil, xibnr, xul, oil, oibnr, oul, cil, cibnr, cul, nil, nibnr, nul, bul, hul, lul, indul As Long
conn.Execute "insert into dbo.Intl_LL (UWU,OBU,Profile_ID, Insured_name, Claim_number,Claim_desc, Event_Name, UY, AY, AQ, Date_of_loss, Region, CCY, Policy_number, Branch, LE, MPL,Claim_alert_email, Comments, [Large Profile Flag], [Earmark Flag], [Tracked for Qtrly dev], [Gross Incurred], [Gross IBNR], [Gross Ultimate], [FAC Incurred], [FAC IBNR], [FAC Ultimate], [QS Incurred],[QS IBNR],[QS Ultimate],[XOL Incurred],[XOL IBNR],[XOL Ultimate],[Ceded OTH Incurred],[Ceded OTH IBNR],[Ceded OTH Ultimate],[Ceded Total Incurred],[Ceded Total IBNR],[Ceded Total Ultimate],[Net Incurred],[Net IBNR],[Net Ultimate],[Booked Ultimate],version)" & _
"values ('" & sUWU & "', '" & sOBU & "','" & sProfile & "', '" & sInsured & "','" & sClaim & "','" & sClmdesc & "','" & sEvent & "','" & sUY & "','" & sAY & "','" & sAQ & "','" & sDOL & "','" & sRegion & "','" & sCCY & "','" & sPolnum & "','" & sBranch & "','" & sLE & "','" & sMPL & "','" & sClaimalert & "','" & sComm & "','" & sLargeF & "','" & sEarF & "','" & sTrackF & "','" & gil & "', '" & gibnr & "','" & gul & "','" & fil & "','" & fibnr & "','" & ful & "','" & qil & "','" & qibnr & "','" & qul & "','" & xil & "','" & xibnr & "','" & xul & "','" & oil & "','" & oibnr & "','" & oul & "','" & cil & "','" & cibnr & "','" & cul & "','" & nil & "','" & nibnr & "','" & nul & "','" & bul & "', '" & ver & "')"
I have ensured that the variables that have Long data type in VBA are numeric(7, 11) type in SQL Server.
Feel free to ask for more information about the problem. Thanks.
MySQL must assume the values are supposed to be the same type as the "mycol" column and silently converts them. - It does the same when you try to compare an INT to a string.
However, you should try not to quote values that are supposed to be numbers. Even if MySQL does automatically convert some of them, it costs a few cycles and the behavior may not be consistent.
Bottom line: always leave numbers unquoted, and only quote strings and dates.

How to insert into a table while ignoring fields with no data?

I wan't to insert data to a table but not all fields are required to be filled some are just optional.
CurrentDb.Execute "INSERT INTO tbl_Records_of_Violation(Serial_Number,Badge,Rank,Lastname,Firstname,Middlename,Qualifier,Gender,Birthdate,Date_Ent_Svc,Address,MotherUnit,Unit,Date_of_Commission,Reporting_Officer,Report_to_Supervisor,Approving_Authority,Punishment,Remarks,Violation1) VALUES ('" & Me.Serial_Number & "','" & Me.Badge & "','" & Me.Rank & "','" & Me.Lastname & "','" & Me.Firstname & "','" & Me.Middlename & "','" & Me.Qualifier & "','" & Me.Gender & "','" & Me.Birthdate & "','" & Me.Date_Ent_Svc & "','" & Me.Address & "','" & Me.MotherUnit & "','" & Me.Unit & "','" & Me.Date_of_Commission & "','" & Me.Reporting_Officer & "','" & Me.Report_to_Supervisor & "','" & Me.Approving_Authority & "','" & Me.Punishment & "','" & Me.Remarks & "'," & Me.Violation1 & ")"
MsgBox "Record has been updated", vbInformation, "Record Information"
I want that even if one of the field is empty it would be saved in my table.
The table tbl_Records_of_Violation has 20 columns of data being inserted by this command.
Each of those 20 columns should be defined as Nullable,
and each of the screen values (Me.xxx) needs to have valid data or nulls.

insert statement error vb.net

following is the code which is use to enter datagridview items into the table.
Dim X As DataGridViewRow
grnno = 123123
glocation = txtlocation.Text
gsupplier = txtsupplier.Text
greceivedby = txtreceivedby.Text
greceiveddate = txtreceiveddate.Text
grn_status = cmbstatus.SelectedItem
ggrossamt = txtgrossamt.Text
gdiscountamount = txtdiscount.Text
gtotalnetamount = txttotalnet.Text
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) values('" & glocation & "','" & gsupplier & "','" & greceivedby & "','" & greceiveddate & "','" & grn_status & "'," & ggrossamt & "," & gdiscountamount & "," & gtotalnetamount & " )"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "','" & X.Cells(6).Value & "','" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
Next
the error is in the 2nd insert statement, it gives error cannot convert string to integer.. the cells from x.cell(6) are of integer type and in database also its integer type, now I want to ask should I enclose it in single quotations or not, as enclosing in single quotations give such errors like syntax '' and in double quotations it gives like cannot convert string to int type.please tell where I am doing wrong.
First of all use parametrized queries! It is safer and also more readable. You are passing some value as string but should be integer.
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) _
values(#glocation, #gsupplier, #greceivedby, #greceiveddate, #grn_status, #ggrossamt, #gdiscountamount, #gtotalnetamount)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#glocation", glocation)
sqlcmd.Parameters.AddWithValue("#gsupplier", gsupplier) //and so on
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) _
VALUES(#grnno, #item_code, #description, ...)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#grnno", grnno)
sqlcmd.Parameters.AddWithValue("#item_code", CType(X.Cells(0).Value, Integer)) //cast to proper type
sqlcmd.ExecuteNonQuery()
Next
Remove the single quote marks ''
For example (and referring only to x.cell(6) as per your post) use " & X.Cells(6).Value & "
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & X.Cells(6).Value & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
You may also need to cast it (assuming it's always going to have a numeric value)
" & CInt(X.Cells(6).Value) &"
I will assume you know of SQL injection and this method of updating a database is generally 'outdated' and 'bad practice' now and you should use parameters instead...
Updated
Since there is a possibility of a null (and you want it to be a 0 where this is the case), you could use something like (not tested as I'm not a VB person)
dim cellSix as integer
if IsNothing(X.Cells(6).Value then
cellSix = 0
else
cellSix = CInt(X.Cells(6).Value)
end if
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & cellSix & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
Or, to keep the code shorter you could use the IIF
cellSix = IIf(isnothing(CInt(X.Cells(6).Value)), 0, CInt(X.Cells(6).Value))

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 "'".