Procedure only updates the first value - vb.net

I have this SQL procedure for updating records given a #StepId value.
I got the values from a hidden field as an array and I loop them.
The problem is that the procedure only updates the first value.
The loop happen but do not update more than 1 value.
my array contains something like {1000,2000,3000,}
my parameters are
#StepId (int)
#DateCalculationRule (char)
#Result (int)
Private Sub buttonCalculateDatesClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonCalculateDates.Click
Dim mySteps As String
Dim myRule As String
Dim ok As Integer = 1
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("cnnstring").ConnectionString
Dim conn As SqlConnection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("SaveStepDeadlineRule", conn)
conn.Open()
conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
myRule = HiddRule.Value
mySteps = HiddStepIDs.Value
'Separate string by comas
Dim parts As String() = mySteps.Split(New Char() {","c})
Dim part As String
For Each part In parts
cmd.Parameters.Add(New SqlParameter("#StepId", part))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", myRule))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next
conn.Close()
End Sub

You will need to clear down your parameters each time you loop:
cmd.Parameters.Clear
This is how it would be used:
For Each part In parts
cmd.Parameters.Clear()
cmd.Parameters.Add(New SqlParameter("#StepId", part))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", myRule))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next
You could create the parameters outside the loop since they don't change and then just assign the value each time you loop:
cmd.Parameters.Add(New SqlParameter("#StepId", 0))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", ""))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
For Each part In parts
cmd.Parameters("#StepId").Value = part
cmd.Parameters("#DateCalculationRule").Value = myRule
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next

Related

Update table in sql database from listview items

Hello folks am trying read from the table identify a specific column if not YES then update my table using items from listview
Public Sub FeesFromSetFees(lst As ListView, Amt As String, Year As String, Clss As String, Term As String, Mode As String)
Dim txtID As New TextBox
Dim txtbal As New TextBox
Dim toText As New TextBox
Dim add As New TextBox
Try
con = New SqlConnection(My.Settings.DeseretConnectionString)
con.Open()
sql = "SELECT * FROM Fees"
command = New SqlCommand(sql, con)
reader = command.ExecuteReader
While reader.Read()
toText.Text = reader.Item("scholarship").ToString
If toText.Text.ToUpper <> "YES" Then
txtID.Text = reader.Item("id").ToString
add.Text = reader.Item("balance").ToString
txtbal.Text = CType(Amt.Trim, Double) + CType(add.Text.Trim, Double)
Dim item As New ListViewItem(txtbal.Text)
item.SubItems.Add(txtID.Text)
lst.Items.Add(item)
Dim lstId As New List(Of String)
Dim lstBalance As New List(Of String)
For Each li As ListViewItem In lst.Items
lstId.Add(li.SubItems(0).ToString)
lstBalance.Add(li.SubItems(1).ToString)
Next
Dim Sql = "Update fees Set class = #Class, year = #Year, mode = #Mode,term = #Term, balance = #Balance where id = #ID"
Using cn As New SqlConnection(My.Settings.DeseretConnectionString)
Using cmd As New SqlCommand(Sql, cn)
With cmd.Parameters
.Add("#Class", SqlDbType.VarChar).Value = Clss
.Add("#Year", SqlDbType.VarChar).Value = Year
.Add("#Mode", SqlDbType.VarChar).Value = Mode
.Add("#Term", SqlDbType.VarChar).Value = Term
.Add("#Balance", SqlDbType.VarChar)
.Add("#ID", SqlDbType.VarChar)
End With
cn.Open()
For index = 0 To lstId.Count - 1
cmd.Parameters("#Balance").Value = lstBalance(index)
cmd.Parameters("#ID").Value = lstId(index)
cmd.ExecuteNonQuery()
Next
End Using
End Using
MessageBox.Show("successful")
End If
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
I get my successful message but nothing really happen to data in the table
Public Sub FeesFromSetFees(Amt As String, Year As String, Clss As String, Term As String, Mode As String)
Dim txtID As New TextBox
Dim txtbal As New TextBox
Dim toText As New TextBox
Dim add As New TextBox
Try
con = New SqlConnection(My.Settings.DeseretConnectionString)
con.Open()
sql = "SELECT * FROM Fees"
command = New SqlCommand(sql, con)
reader = command.ExecuteReader
While reader.Read()
toText.Text = reader.Item("scholarship").ToString
If toText.Text.ToUpper <> "YES" Then
txtID.Text = reader.Item("id").ToString
add.Text = reader.Item("balance").ToString
txtbal.Text = CType(Amt.Trim, Double) + CType(add.Text.Trim, Double)
Dim Sql = "Update fees Set class = #Class, year = #Year, mode = #Mode,term = #Term, balance = #Balance where id = #ID"
Using cn As New SqlConnection(My.Settings.DeseretConnectionString)
Using cmd As New SqlCommand(Sql, cn)
With cmd.Parameters
.Add("#Class", SqlDbType.VarChar).Value = Clss
.Add("#Year", SqlDbType.VarChar).Value = Year
.Add("#Mode", SqlDbType.VarChar).Value = Mode
.Add("#Term", SqlDbType.VarChar).Value = Term
.Add("#Balance", SqlDbType.VarChar).Value = txtbal.Text
.Add("#ID", SqlDbType.VarChar).Value = txtID.Text
cn.Open()
cmd.ExecuteNonQuery()
End With
End Using
End Using
MessageBox.Show("successful")
End If
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Insert string into different tables based on combobox selection

1st off, my apologies if this question has been asked. I have looked but haven't found an exact answer to the problem I'm facing. Secondly, I must stress that, I am not a developer, I'm an engineer and only writing sowftware as a needs must situation.
I have a form which passes data to an access db (This works). However I need to update it so that it will pass the information to different tables within the same db based upon a selection in a combobox. For instance if combobox selection = X then insert into tableX, if combobox = Y then insert into tableY. Any and all help is appreciated.
I've tried using If statements in order to select the appropriate table, but this doesn't work.
Imports System.Data.OleDb
Public Class Form1
Public ds As New DataSet
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim rs As New resizer
Dim cmd As OleDbCommand
Private con As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
provider = "Provider=Microsoft.Jet.OleDb.4.0;Data Source="
dataFile = "R:\Quality\NCR-Access_Database\NCRdb1.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = ""
If ComboBox2.SelectedText = "Assembly" Then
str = "Insert into [ASSEMBLYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Grinding" Then
str = "Insert into [GRINDINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Milling" Then
str = "Insert into [MILLINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Mill-Turn" Then
str = "Insert into [MILL-TURNtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Turning" Then
str = "Insert into [TURNINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Supplier" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Subcon" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Quality" Then
str = "Insert into [QUALITYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
End If
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("NCR-No", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Week-No", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("Part-No", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("Drawing_Rev", TextBox5.Text))
cmd.Parameters.Add(New OleDbParameter("Description", TextBox6.Text))
cmd.Parameters.Add(New OleDbParameter("W/O-No", TextBox7.Text))
cmd.Parameters.Add(New OleDbParameter("Operator-No", TextBox8.Text))
cmd.Parameters.Add(New OleDbParameter("Operation-No", TextBox9.Text))
cmd.Parameters.Add(New OleDbParameter("Machine-No", TextBox10.Text))
cmd.Parameters.Add(New OleDbParameter("Section", ComboBox2.Text))
cmd.Parameters.Add(New OleDbParameter("Batch-Qty", TextBox12.Text))
cmd.Parameters.Add(New OleDbParameter("Reject_Qty", TextBox13.Text))
cmd.Parameters.Add(New OleDbParameter("Disposition", TextBox14.Text))
cmd.Parameters.Add(New OleDbParameter("Mat-Cost", TextBox15.Text))
cmd.Parameters.Add(New OleDbParameter("Standard-Cost", TextBox16.Text))
cmd.Parameters.Add(New OleDbParameter("Defect-Description", RichTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Fault-Code", TextBox17.Text))
cmd.Parameters.Add(New OleDbParameter("Dept", TextBox18.Text))
cmd.Parameters.Add(New OleDbParameter("Root-Cause", RichTextBox2.Text))
cmd.Parameters.Add(New OleDbParameter("NCR-Pinksheet", ComboBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Permanent-Action", RichTextBox3.Text))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox1.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox3.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
ComboBox2.ResetText()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
RichTextBox1.Clear()
TextBox17.Clear()
TextBox18.Clear()
RichTextBox2.Clear()
ComboBox1.ResetText()
RichTextBox3.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When submitting I get a dialog that states "Command text was not set for the command object". If i submit again, then I get an exception unhandled event in VS --- "System.InvalidOperationException: 'Not allowed to change the 'ConnectionString' property. The connection's current state is open.'"
use INSERT INTO syntax
INSERT INTO table-name (column-names)
VALUES (values)
SQL INSERT INTO with SELECT like this
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1),
SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100),
City, Country, Phone
FROM Supplier
WHERE CompanyName = 'casterx.co'

if the input value is in between two values then display the result

I have a SQL table with three columns "From","To" and "Equivalent Value". Each value is shown below:
From To Equivalent Value
1,001.00 2,000.00 200.00
2,001.00 3,000.00 300.00
Now if the user enters the value "1,200.00" in textbox1 it will display the result value to textbox2 which is "200.00" because that is the corresponding value of between "From" and "To.
Another condition, if the user enters the value "2,500.00" in textbox1 it will display the value "300.00".
So far, I have tried this code but no luck:
Dim conn As SqlConnection = SQLConn()
Dim da As New SqlDataAdapter
Dim dt As New DataTable
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim result As String
cmd.CommandText = "SELECT [Equivalent Value] FROM tblSSS"
result = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
If result <> "" Then
If TextBox1.Text >= dt.Rows(0)(1).ToString() And TextBox1.Text <= dt.Rows(0)(2).ToString() Then
TextBox2.Text = dt.Rows(0)(3).ToString()
End If
End If
If I have got this right I think there are a couple of things I would change which may help you:
Use Using. This will dispose of the SQL objects once finished with.
Use SqlParameters. This will help with filtering your data.
Remove the use of SqlDataAdapter. In this case I don't feel it's needed.
The use of IIf. I will be using If which has replaced IIf.
With these in mind I would look at something like this:
Dim fromValue As Decimal = 0D
Dim toValue As Decimal = 0D
If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then
Dim dt As New DataTable
Using conn As SqlConnection = SQLConn,
cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue})
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count = 1 Then
TextBox2.Text = If(IsDBNull(dt.Rows(0).Item("Equivalent Value")), "0", dt.Rows(0).Item("Equivalent Value").ToString)
End If
End If
Note the use of Decimal.TryParse:
Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.
This is an assumption that the From and To fields in your database are Decimal.
Now to explain the difference between IIf and If. IIf executes each portion of the statement even if it's true whilst If executes only one portion. I won't go into detail as many others on here have done that already. Have a look at this answer.
As per Andrew Morton's comment and more in line with what the OP attempted here is a solution that uses ExecuteScaler.
ExecuteScaler executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
With this in mind:
'I reset the value of TextBox2.Text. You may not want to.
TextBox2.Text = ""
Dim fromValue As Decimal = 0D
Dim toValue As Decimal = 0D
If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then
Using conn As SqlConnection = SQLConn,
cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue})
conn.Open()
Try
TextBox2.Text = cmd.ExecuteScalar().ToString()
Catch ex As Exception
End Try
End Using
End If
I have used the example on the ExecuteScaler MSDN documentation. You might want to look into handling the exception on the Try Catch a little better and not letting it go to waste.
You may want to place this code on the TextBox1.Leave method or maybe on a Button.Click method. That's totally up to you.
There may a few changes you may need to make however I think this will give you a few ideas on how to move ahead with your code.
Hope it Helps...
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "SELECT [Equivalent Value] FROM tblSSS WHERE [FROM]<=" & Val(TextBox1.Text) & " AND [TO]>= " & Val(TextBox1.Text)
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try

Looping through SQLdatareader and comparing row values

I have a function that calls a stored procedure. I need to compare the result to an input parameter. I keep getting a warning that the function does not return on all code paths, but I can't figure out where.
So, 2 questions:
1. Am I looping through the SqlDataReader correctly or should I fill a datatable with my reader results?
2. Where am I missing a return value?
Function code:
Function FZCheck(FZ As String) As Boolean
Dim constr As String = My.Settings.devTOD.ToString
Dim con As New SqlConnection(constr)
Dim cmd As New SqlCommand("spSelectFloodZones", con)
cmd.CommandType = CommandType.StoredProcedure
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
If rdr.HasRows Then
Do While rdr.Read
If String.Equals(rdr(0).ToString, FZ) = True Then
Return True
Else
Return False
End If
Loop
Else
Return False
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
rdr.Close()
End Function
Stored proc code: (very simple)
ALTER PROCEDURE [dbo].[spSelectFloodZones]
AS
SET NOCOUNT ON
SET ROWCOUNT 0
-- ====================
-- Select flood zones
-- ====================
SELECT DISTINCT FloodZone
FROM TOD.dbo.FloodZones
Language is VB.NET, using SQL Server 2012.
Here you go with some minor refactoring.
Function FZCheck(FZ As String) As Boolean
Dim constr As String = My.Settings.devTOD.ToString
Dim con As New SqlConnection(constr)
Dim result As Boolean = False
Dim cmd As New SqlCommand("spSelectFloodZones", con)
cmd.CommandType = CommandType.StoredProcedure
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
If rdr.HasRows Then
Do While rdr.Read
If String.Equals(rdr(0).ToString, FZ) = True Then
result = True
End If
Loop
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
rdr.Close()
Return result
End Function

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