Asp.net Sql Insert rows using select case - asp.net

Im designing a website that allows a user to update a database with information. The problem I am having is that I have created various controls that are hidden when the page loads, but the user can click to unhide to add additional info.
The issue I am coming up against is writing the sql statement to handle identifying what controls are used. I have a viewstate count to let me know which panels are visible or not.
ViewState("count") = CInt(ViewState("count")) + 1
Label1.Text = ViewState("count").ToString()
And then the code behind to write the SQL query I have looks like this
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring As String
Dim dd As String
Dim mm As String
Dim yy As String
dd = Left(TextBox1.Text, 2)
mm = Mid(TextBox1.Text, 4, 2)
yy = Right(TextBox1.Text, 4)
myConn = New SqlConnection("xxx")
myConn.Open()
Select Case Label1.Text
Case Is = "0"
sqlstring = "INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate, Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
Case Is = "1"
sqlstring = "INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate, Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "') VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList4.SelectedValue & "','" & TextBox7.Text & "','" & TextBox9.Text & "','" & TextBox8.Text & "'," & DropDownList5.SelectedValue & "," & TextBox10.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End Select
cmd = New SqlCommand(sqlstring, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
Response.Redirect(Request.RawUrl, True)
End Sub
My problem lies in the select case as when case is 1 it is only inserting the first values and not the second set. I have up to 6 "cases" to choose from, each time adding an additional set of values. Sql server is 2008
Any help is appreciated

I may be wrong but in the second statement the clause VALUES appears two two times.
That might be the source of your problem.

as above however you are going to end up with a horribly long string by the 6th case might want to re-engineer it to check >= each value if the previous strings are immutable

From SQL Server 2008 onwards, you can use the multi-values insert clause that looks like this
INSERT [INTO] tbl [(...columns...)]
VALUES (....),(....),(....);
You have constructed your query like this
INSERT [INTO] tbl [(...columns...)]
VALUES (....)
VALUES (....)
VALUES (....)
I would also personally have constructed the string concatenation not using a SELECT-CASE block:
If Label1.Text >= "0" Then
sqlstring = "('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End If
If Label1.Text >= "1" Then
sqlstring = sqlstring + "," + "('" & yy & "-" & mm & "-" & dd & "','" & DropDownList4.SelectedValue & "','" & TextBox7.Text & "','" & TextBox9.Text & "','" & TextBox8.Text & "'," & DropDownList5.SelectedValue & "," & TextBox10.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End If
' etc
If for whatever arcane reason the multi-values statement doesn't work, you can always rely on the tried and true multi-statement batch, i.e.
If Label1.Text >= "0" Then
sqlstring = "INSERT ... VALUES (...);"
End If
If Label1.Text >= "1" Then
sqlstring = sqlstring + "INSERT ... VALUES (...);"
End If
If Label1.Text >= "2" Then
sqlstring = sqlstring + "INSERT ... VALUES (...);"
End If
' etc
Note the semicolon statement terminators within the batch.

The issue was not the select case but the viewstate not passing to the sql string correctly, I know possibly not the best solution but passed the label.text to a hidden textbox, which the sql string was able to read properly. Richard's suggestion to use a concatenated IF statement instead of Select Case was a great idea!
Thanks for all the help

Related

i show this error Conversion failed when converting datetime from character string

I want to save the number of fields in the Data Grid View, and then stored in the Database.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim sql As String
For i As Integer = 0 To dgvContract.Rows.Count - 1
sql = "INSERT INTO ContractDetails(Customer_ID , Customer_Name , Contract_ID , Contract_Name ,Strat_Date , End_Date , Value , Description) VALUES(" & (dgvContract.Item("dgvCustomerID", i).Value) & ",'" & (dgvContract.Item("dgvCustomerName", i).Value) & "','" & (dgvContract.Item("dgvContractID", i).Value) & "','" & (dgvContract.Item("dgvContractName", i).Value) & "','" & Format(dgvContract.Item("dgvStratingDate", i).Value, "mm/dd/yyyy") & "','" & Format(dgvContract.Item("dgvEndDate", i).Value, " mm/dd / yy") & "','" & (dgvContract.Item("dgvValue", i).Value & "','" & (dgvContract.Item("dgvDescription", i).Value)) & "')"
SqlHelper.ExecuteScalar(My.Settings.conn, CommandType.Text, sql)
Next
End Sub
It shows me this error:
Conversion failed when converting datetime from character string.

how can i using 2 INSERT INTO statement to store different data

I have these two sql statements. But while executing,it show 'Syntax error in INSERT INTO statement.'
Dim sqlString As String
sqlString = "INSERT INTO CreditCardRecord(CustomerEmail, CardholderName,
CreditCardNo, CCExpMonth, CCExpYear, CVCNo, CardIssuingBank,
Amount) VALUES ('" & Master.cEmailDOnMasterPage & "','" &
cardholderName & "','" & creditCardNo & "','" & ccExpMonth & "',
'" & ccExpYesr & "','" & cvc & "','" & cardIssuingBank & "',
'" & totalamount & "')"
Dim sqlcommand As New OleDbCommand(sqlString, db)
sqlcommand.ExecuteNonQuery()
Dim customerRervation As String
customerRervation = "INSERT INTO CustomerReservation(CustomerEmail,
CustomerFN, CustomerLN, CustomerIdentityCard,
CustomerPhoneNo, Package, Table, Amount, BookingDate)
VALUSE ('" & Master.cEmailDOnMasterPage & "',
'" & customerFN & "','" & customerLN & "',
'" & customerIC & "','" & customerPhoneNo & "',
'" & lblShowPackage.Text & "','" & lblShowTable.Text &
"','" & totalamount & "','" & lblShowDate.Text & "')"
Dim sqlcommand2 As New OleDbCommand(customerRervation, db)
sqlcommand2.ExecuteNonQuery()
The issue in your 2nd sql query statement. You are wrongly spelled VALUES to VALUSE. so instead of VALUSE, use VALUES.
Dim customerRervation As String
customerRervation = "INSERT INTO CustomerReservation(CustomerEmail,
CustomerFN, CustomerLN, CustomerIdentityCard,
CustomerPhoneNo, Package, Table, Amount, BookingDate)
VALUES ('" & Master.cEmailDOnMasterPage & "',
'" & customerFN & "','" & customerLN & "',
'" & customerIC & "','" & customerPhoneNo & "',
'" & lblShowPackage.Text & "','" & lblShowTable.Text &
"','" & totalamount & "','" & lblShowDate.Text & "')"
Dim sqlcommand2 As New OleDbCommand(customerRervation, db)
sqlcommand2.ExecuteNonQuery()
Just add [] can already
Dim customerRervation As String
customerRervation = "INSERT INTO CustomerReservation([CustomerEmail],
[CustomerFN], [CustomerLN], [CustomerIdentityCard],
[CustomerPhoneNo], [Package], [Table], [Amount], [BookingDate])
VALUES ('" & Master.cEmailDOnMasterPage & "',
'" & customerFN & "','" & customerLN & "',
'" & customerIC & "','" & customerPhoneNo & "',
'" & lblShowPackage.Text & "','" & lblShowTable.Text &
"','" & totalamount & "','" & lblShowDate.Text & "')"
Dim sqlcommand2 As New OleDbCommand(customerRervation, db)
sqlcommand2.ExecuteNonQuery()

Cannot insert decimal from textbox into database

I am struggling with getting my sql database to accept a decimal from a textbox on my website page. When I enter a whole number there is no issue, it is only when I enter a decimal (123.45) that I get the issue. I have tried double.parse(textbox.text) and decimal.parse(textbox.text) to no avail.
I get the error message
input string was not in the correct format
My insert statement is below:
"INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate,
Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd &
"','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" &
TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue &
"," & Double.Parse(TextBox6.Text) & "," & TextBox27.Text & ",'" &
DropDownList1.SelectedValue & "'); INSERT INTO Cash (Date, Bank_Account,
Amount, Document_Number) VALUES ('" & yy & "-" & mm & "-" & dd & "','" &
DropDownList1.SelectedValue & "'," & Double.Parse(TextBox2.Text) & "," &
TextBox27.Text & ");"
My database field is set to decimal(18,2) Any ideas?
Your error message is telling that input string was not in the correct format. Means that you are trying to convert wrong value to decimal.
Put a try/catch around the code to see what is being passed in to ParseDouble. This should help determine what is causing the problem and that should help determine where it is coming from. Is a user entering it in a textbox?
Please try "double.TryParse" in place of "Double.Parse".
double temp = 0;
if (double.TryParse("123.456", out temp)
{
Console.WriteLine(string.Format("Parsed temp: {0}", temp);
}
else
{
Console.WriteLine("Input value was not able to be parsed.");
}

How can I ensure that only data entered gets inserted into the db?

Hello again and please forgive me for posting again. I do this when I realize I am having problem fixing it myself.
Please take a look at the code below. I was told by the individual that developed it originally that the code only adds the rows of data the user entered. In other words, there 5 rows of textboxes. A user can enter data into one row or into all 5 rows. If the user enters data into one row of textbox, that's what gets inserted into the db.
I made some minor change to the code so that users can tell when a payment is made by check or cash payment.
Since I made that change, whether a user enters data into one row or all 5 rows, all 5 rows get inserted into the db.
How can I modify this code to ensure only rows entered get inserted?
I am really,really sorry for bothering you guys again and many thanks for all your help.
For x = 1 To 5 Step 1
dedval = obr.FindControl("ded" & CStr(x))
chckvalflag = obr.FindControl("chck" & CStr(x))
checkboxval = obr.FindControl("chckBox" & CStr(x))
onetimeval = obr.FindControl("onetime" & CStr(x))
chcknumval = obr.FindControl("chcknum" & CStr(x))
multival = obr.FindControl("multi" & CStr(x))
*If (chckvalflag.Text <> "" Or chckvalflag.Text <> "0") And Not checkboxval.Checked Then
cashval = DirectCast(obr.FindControl("chck" & CStr(x)), TextBox).Text
chckval = ""
chcknumval.Text = "Cash Payment"
Else
chckval = DirectCast(obr.FindControl("chck" & CStr(x)), TextBox).Text
chcknumval = obr.FindControl("chcknum" & CStr(x))
End If*
If dedval.Text <> "-1" And donatechoice.SelectedItem.Value <> "No" Then
sql += "INSERT INTO Contribs (employee_id, charity_code, check_amt, chcknum, one_time, bi_weekly, cash, donate_choice, date_stamp) "
sql += "VALUES ('" & Replace(employee_idLabel.Text, "'", "''") & "','" & Replace(dedval.SelectedValue, "'", "''") & "','" & Replace(chckval, "'", "''") & "','" & Replace(chcknumval.Text, "'", "''") & "','" & Replace(onetimeval.Text, "'", "''") & "','" & multival.Text & "','" & Replace(cashval, "'", "''") & "','" & Replace(donatechoice.SelectedItem.Value, "'", "''") & "','" & Replace(datestamp, "'", "''") & "');"
End If
If donatechoice.SelectedItem.Value = "No" Then
x = 6
sql += "INSERT INTO Contribs (employee_id, charity_code, check_amt, chcknum, one_time, bi_weekly, cash, donate_choice, date_stamp) "
sql += "VALUES ('" & Replace(employee_idLabel.Text, "'", "''") & "','" & Replace(dedval.SelectedValue, "'", "''") & "','" & Replace(chckval, "'", "''") & "','" & Replace(chcknumval.Text, "'", "''") & "','" & Replace(onetimeval.Text, "'", "''") & "','" & Replace(multival.Text, "'", "''") & "','" & Replace(cashval, "'", "''") & "','" & Replace(donatechoice.SelectedItem.Value, "'", "''") & "','" & Replace(datestamp, "'", "''") & "');"
End If
Next
Just add some conditions to validate the data was entered into the inputs in each row.
If Not String.IsNullOrEmpty(String.Concat(TextBox1.Text, TextBox2.Text, TextBox3.Text)) Then
'insert logic here
End If
On a side note, I would suggest modifying the code to use parameters instead. The code is ripe for SQL-injection.
Look into using parametrized stored procedures instead of building your SQL as a string. Right now your application can be SQL injected. If you gave me a link to your application, I could wipe out all the data in your Contribs table (assuming the identity the thread is running under has permission; regardless, your query can be killed via syntax based on user input).
If you only want to insert records depending on what textboxes the user filled out, just use a case statement or if block to check for values in those textboxes. If the user entered a value, execute a function which hits the database.

Insert into Access DB (loop)

I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.

Resources