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?
Related
How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
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.
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
i've been fumbling with this problem for a while now. am trying to update/insert into my access database data from a datagridview on a form.
i've a maskedtextbox that i've masked to suit my primary key. when the mask is completed then automatically, records are read from the database to the textboxes and datagridview as shown in the attached picture.
i did that with this code
If STHN_ID.MaskCompleted = True Then
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
'da = New OleDbDataAdapter("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn) 'Change items to your database name
'da.Fill(ds)
'Dim view As New DataView(tables(0))
'source1.DataSource = view
'DependantView.DataSource = view
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
'connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DependantView.DataSource = myTable
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
my headache now is to update/insert into the database when records are added/edited in the datagridview based on the STHN_ID entered in the maskedtextbox. any help would be really appreciated.
sample
this is how i got it done!
on maskedtextbox with mask completed this is the code to read from database and load datagridview ...........
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
con = New OleDbConnection
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\PRINCE\Documents\STHNDatabase.accdb")
con.Open()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
Dim connection As New OleDbConnection
connection.ConnectionString = connString
adapt = New OleDbDataAdapter("Select [DependentID],[DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship],[STHN_ID] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", con)
ds = New DataSet
adapt.Fill(ds, "DependantData")
DependantView.DataSource = ds.Tables(0)
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
and on the SaveButton Click this is the code.....
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Try
builder = New OleDbCommandBuilder(adapt)
adapt.Update(ds, "DependantData")
MsgBox("Updated Successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks once again. really appreciate it
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