vb.net message: no value given for one or more required parameters - vb.net

I made a POS project but when i save the data to access database the error is shown:
no value given for one or more required parameters.
My code is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim MyConnection As OleDb.OleDbConnection = Nothing
Dim MyTransaction As OleDb.OleDbTransaction = Nothing
Try
'create the connection and transaction object
MyConnection = New OleDb.OleDbConnection(My.Settings.dbConnectionString)
MyConnection.Open()
MyTransaction = MyConnection.BeginTransaction
'insert the new recipt
Dim SQL As String = "insert into recipts (ReciptDate, ReciptTotal) values (:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = MyConnection
CMD1.Transaction = MyTransaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
'get the id for the recipt
SQL = "Select max (reciptId) as MAXID from recipts"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = MyConnection
CMD2.Transaction = MyTransaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
'insert the details of the recipt
Dim I As Integer
For I = 0 To DGV2.Rows.Count - 1
'get the values
Dim Barcode As String = DGV2.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV2.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV2.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV2.Rows(I).Cells(4).Value
'next create a command
Dim CMD3 As New OleDb.OleDbCommand
SQL = "insert into ReciptDetails" & _
"(ReciptId, Barcode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4)"
CMD3.Connection = MyConnection
CMD3.Transaction = Mytransaction
CMD3.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", ReciptID)
CMD1.Parameters.AddWithValue(":1", Barcode)
CMD1.Parameters.AddWithValue(":2", ItemCount)
CMD1.Parameters.AddWithValue(":3", BuyPrice)
CMD1.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
'all well save the changes
Mytransaction.Commit()
'close conncetion
Mytransaction.Dispose()
MyConnection.Close()
MyConnection.Dispose()
DGV2.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Mytransaction IsNot Nothing Then
Mytransaction.Rollback()
End If
If MyConnection IsNot Nothing Then
If MyConnection.State = ConnectionState.Open Then
MyConnection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
What is the problem here?

Simple typo. In your CMD3 you're adding all the parameters to CMD1
Hence CMD3 has 5 missing parameters.

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

The right way to save 2 table to access database in vb,net

I tried to save all of records of 2 tables to Access database. My idea is save first table then save next table. But I think it isn't the right way when save multi tables to access because It take a long time.
Here is my code and it run ok but I don't know is there another ways which better to save multi tables to access.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
Dim cmdupdate As String
Dim cmdinsert As String
For Each dr In dt.Rows
cmdupdate = "UPDATE StudentData SET ID=#ID, StudentName=#StudentName, StudentID=#StudentID, StudentClass=#StudentClass WHERE StudentID=#StudentID"
cmdinsert = "INSERT INTO StudentData(ID,StudentName,StudentID,StudentClass) VALUES(#ID,#StudentName,#StudentID,#StudentClass)"
cmd.Parameters.Clear()
cmd.CommandText = cmdupdate
cmd.Parameters.AddWithValue("#ID", dr("ID"))
cmd.Parameters.AddWithValue("#StudentName", dr("StudentName"))
cmd.Parameters.AddWithValue("#StudentID", dr("StudentID"))
cmd.Parameters.AddWithValue("#StudentClass", dr("StudentClass"))
cnn.Open()
Dim count = cmd.ExecuteNonQuery()
If count = 0 Then
cmd.CommandText = cmdinsert
cmd.ExecuteNonQuery()
End If
cnn.Close()
Next
For Each dr2 In dt2.Rows
cmdupdate = "UPDATE StudentData2 SET ID2=#ID2, StudentName2=#StudentName2, StudentID2=#StudentID2, StudentClass2=#StudentClass2 WHERE StudentID2=#StudentID2"
cmdinsert = "INSERT INTO StudentData2(ID2,StudentName2,StudentID2,StudentClass2) VALUES(#ID2,#StudentName2,#StudentID2,#StudentClass2)"
cmd.Parameters.Clear()
cmd.CommandText = cmdupdate
cmd.Parameters.AddWithValue("#ID2", dr2("ID2"))
cmd.Parameters.AddWithValue("#StudentName2", dr2("StudentName2"))
cmd.Parameters.AddWithValue("#StudentID2", dr2("StudentID2"))
cmd.Parameters.AddWithValue("#StudentClass2", dr2("StudentClass2"))
cnn.Open()
Dim count2 = cmd.ExecuteNonQuery()
If count2 = 0 Then
cmd.CommandText = cmdinsert
cmd.ExecuteNonQuery()
End If
cnn.Close()
Next
End Sub

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

How to Update sql table with data from excel sheet in vb.net

I am having problem updating sql table with excel sheet. The fact is that, am working on this small project where the user can first of all export or print out a class list with StudentNumber,SubjectID, ClassScore, ExamScore to excel sheet by clicking a button in vb.net application and then edit the sheet by filling in the ClassScore and ExamScore, then upload the sheet back to sql through vb.net.
The question is how to check if the current StudentNumber or row exist in sql table then update the table else insert a new row.
This is my code using the SQLBulk Copy, left with updating the sql table all in vb.net
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
If ofd.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then Exit Sub
' Dim dgv As System.Windows.Forms.DataGridView
With ofd
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
Dim nme As String = ofd.FileName
Import(nme, dgv)
End Sub
Public Shared Function Import(ByVal FileName As String, ByVal dgv As DataGridView) As Boolean
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=Excel 12.0 Xml;")
'MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Scores")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dgv.DataSource = DtSet.Tables(0)
MyConnection.Close()
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=xxxx-PC;Initial Catalog=TryExcel;Persist Security Info=True;User ID=xx;Password=xxxx"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, MyConnection)
Dim objDR As OleDbDataReader
SQLconn.ConnectionString = ConnString
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnString)
bulkCopy.DestinationTableName = "Scores"
MyConnection.Open()
objDR = objCmdSelect.ExecuteReader
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
End Using
Return True
End Function
Private Shared Function safefilename() As String
Throw New NotImplementedException
End Function
Private Sub Upload_Workbook()
Dim t As New Thread(New ThreadStart(Sub()
dt = New DataTable
dt = New DataTable("Table_Name")
dt.Columns.Add("Column_1")
dt.Columns.Add("Column_2)
dt.Columns.Add("Column_3")
dt.Columns.Add("Column_4")
dt.Columns.Add("Column_5")
dt.Columns.Add("Column_6")
dt.Columns.Add("Column_7")
ds = New DataSet
ds.Tables.Add(dt)
Dim i As Integer
For i = 2 To (Cells(1, 11).Text)
dr = dt.NewRow
dr(0) = Cells(i, 1).Text
dr(1) = Cells(i, 2).Text
dr(2) = Cells(i, 3).Text
dr(3) = Cells(i, 4).Text
dr(4) = Cells(i, 5).Text
dr(5) = Cells(i, 6).Text
dr(6) = Cells(i, 7).Text
dt.Rows.Add(dr)
Next i
trans = con.BeginTransaction
Try
Dim row As Integer
While (row < dt.Rows.Count)
Dim cmd As New SqlCommand("Sheet1_Upload", con, trans)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("Column_1", dt.Rows(row).ItemArray(0))
cmd.Parameters.AddWithValue("Column_2", dt.Rows(row).ItemArray(1))
cmd.Parameters.AddWithValue("Column_3", dt.Rows(row).ItemArray(2))
cmd.Parameters.AddWithValue("Column_4", dt.Rows(row).ItemArray(3))
cmd.Parameters.AddWithValue("Column_5", dt.Rows(row).ItemArray(4))
cmd.Parameters.AddWithValue("Column_6", dt.Rows(row).ItemArray(5))
cmd.Parameters.AddWithValue("Column_7", dt.Rows(row).ItemArray(6))
cmd.ExecuteNonQuery()
row = row + 1
End While
trans.Commit()
Catch ex As Exception
MsgBox(ex.Message)
trans.Rollback()
End Try
End Sub))
t.Start()
End Sub
'''''''SQL Stored Procedure'''''''
Create procedure Sheet1_Upload(#Column_1 varchar(50),#Column_2 varchar(50),#Column_3 varchar(50),#Column_4 varchar(50),#Column_5 varchar(50),#Column_6 varchar(50))
as
begin
Insert INTO Table_Name(Column_1,Column_2,Column_3,Column_4,Column_5,Column_6) Values(#Column_1,#Column_2,#Column_3,#Column_4,#Column_5,#Column_6)
end
Please create this project on Visual Basic>Office/Share Point>Excel 2013 Workbook.File Path Image
Then open the workbook using another program.
oXL = CreateObject("Excel.Application")
oXL.Visible = False
oWB = oXL.Workbooks.Open("D:\workbook.xlsm")
oWB.Activate()
oWB.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoOpen)
Use excel Auto_Open macro and sheet changed event in VB.net.

error :ExecuteNonQuery: CommandText property has not been initialized

this code is in the button click , i get each data out using spilt
but i encounter error at "cmd.CommandType = CommandType.Text"
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
the same code , the below work
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO GuestList (groupID,guest,contact,eEmail,relationship,info,customerID) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5), Session("customerID"))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
You never set the CommandText property.
You don't need to set CommandType at all.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
dim dt as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblGender )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox1
.DataSource = dt
.DisplayMember = "Gender"
End With
dim dt1 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblStatus )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox2
.DataSource = dt1
.DisplayMember = "Status"
End With
dim dt2 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblDepartment )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox3
.DataSource = dt2
.DisplayMember = "Department"
End With
End Sub
See this
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
'Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
'If item.Contains(",") Then
' splitItems = item.Split(",".ToCharArray())
' sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
'End If
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}({1},'{2}'); ", sqlStatement, splitItems(0), splitItems(1))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try