Data from input box not inserting in to database - asp.net

I made this form to insert information in database. I don't know where the error coming from. It's not inserting information from input fields to database.
Here's my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim id, name, description, code, cat_industry, cat_theme, cat_occasion, cat_budget As String
id = product_id.Text
name = product_name.Text
description = product_description.Text
code = item_code.Text
cat_industry = industry.SelectedValue
cat_theme = theme.SelectedValue
cat_occasion = occasion.SelectedValue
cat_budget = budget.SelectedValue
Try
Dim str1 As String = "insert into product (ID, Product_Name, Product_Description, Item_Code, Industry, Theme, Occasion, Budget) values ('" + id + "', '" + name + "', '" + description + "', '" + code + "', '" + cat_industry + "', '" + cat_theme + "', '" + cat_occasion + "', '" + cat_budget + "')"
con.Open()
Dim cmd As New SqlCommand(str1, con)
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub

Your column names can't be referenced as Product Name and Product Description with a space - you will need to escape it as [Product Name], [Product Description] etc.
But please refrain from inserting data directly - instead you should be parameterizing your input variables. This has benefits from both a performance and security (Sql Injection) perspective.
Dim str1 As String = "insert into product (ID, [Product Name], [Product Description], Item_Code, etc) " _
" values (#id, #name, #description, #code, etc)"
con.Open()
Dim cmd As New SqlCommand(str1, con)
cmd.Parameters.AddWithValue("#id", id )
cmd.Parameters.AddWithValue("#name", name )
... etc
cmd.ExecuteNonQuery()

Related

Insert data in MySQL

When I click on the button it should insert this data in database, but this doesn't happen. It just shows me a MsgBox and doesn't load the insert order.
Private Sub Button1_Click (sender As Object, e As EventArgs) Handles Button1.Click
Dim s As MySqlConnection = servconn("localhost", "root", "123")
If s.State = ConnectionState.Connecting Then
Using insert As MySqlCommand = s.CreateCommand
insert.Connection = s
insert.CommandType = CommandType.Text
insert.CommandText = "insert INTO exam.app (ID, UserName, Email, address) VALUES (NULL, '" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "')"
ID = Convert.ToInt32(insert.ExecuteScalar())
End Using
End If
MsgBox("Inserted commpleted")
End Sub

How to upload xls file's data to SQL Server in devexpress popup control?

I have enquiry on how to insert xls file data into SQL Server. The upload button, and gridview control are placed inside the devexpress popup control and the code works without the popup control but doesn't work with popup control. When I inserted the xls file and clicked the upload button, the label display showed "Please select a file to upload!" although I have did this.
ASP.NET markup:
<dx:ASPxPopupControl ID="popupControl" ClientInstanceName="popupControl"
AllowDragging="true" ShowOnPageLoad="false" runat="server" AllowResize="true" >
<ContentCollection>
<dx:PopupControlContentControl runat="server">
<div class="flexs">
<dx:ASPxUploadControl ID="XXUpload" runat="server" UploadMode="Auto" ValidationSettings-AllowedFileExtensions=".xls" width="500px" >
</dx:ASPxUploadControl>
<dx:ASPxLabel ID="Label2" runat="server" Text=""></dx:ASPxLabel>
<dx:ASPxButton ID="DataUpload" runat="server" Text="UPLOAD" OnClick="DataUpload_Click ">
</dx:ASPxButton>
<dx:ASPxGridView ID="UpdateSplitGrid" ClientIDMode="Static" ClientInstanceName="UpdateSplitGrid" runat="server" Width="200%" DataSourceID="dtSource2" Theme="DevEx" >
.....
</dx:ASPxGridView>
</div>
</dx:PopupControlContentControl>
</ContentCollection>
</dx:ASPxPopupControl>
Vb.net code:
Function uploadExcel1(filePath As String) As String
Dim str As String = ""
Dim namestr1 As String = XXUpload.UploadedFiles.ToArray(0).FileName.ToString
If namestr1 <> "" Then
If Not XXUpload.UploadedFiles.ToArray(0).IsValid Then
str = "Fail to Upload " + namestr1
Else
XXUpload.UploadedFiles.ToArray(0).SaveAs(filePath)
str = " Successfully Uploaded!"
End If
Else
str = "Please select a File to upload!"
End If
Return str
End Function
Function getDTe(filename As String, ByVal sql As String) As DataTable
Dim dt As New DataTable()
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';"
Dim connection As New OleDbConnection(connectionString)
Dim adapter As New OleDbDataAdapter(sql, connection)
adapter.Fill(dt)
Return dt
End Function
Protected Sub DataUpload_Click(sender As Object, e As EventArgs)
Dim filepath As String = "C:\New folder\" + XXUpload.UploadedFiles.ToArray(0).FileName.ToString + ".xls"
Dim msg As String = uploadExcel1(filepath)
Label2.Text = msg
If msg.Contains("Successfully") Then
Dim sql As String = "select * from [Sheet1$]"
Dim dt As New DataTable
dt = getDTe(filepath, sql)
If dt.Rows.Count > 0 Then
Dim i As Integer = 0
Dim colname() As String = {"LotID", "Split_Cat", "Engr_Time", "PLANDESC", "STEPSEQ", "EQPTYPE", "PPID", "STEPDESC", "Split", "Recipe", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22"}
For Each dc As DataColumn In dt.Columns
If dc.ColumnName.ToString <> colname(i) Then
Label2.Text = " File is not in correct format - Details: " + dc.ColumnName.ToString
Return
End If
i = i + 1
Next
For Each dr In dt.Rows
Try
Dim LotID As String = dr("LotID").ToString
Dim Split_Cat As String = dr("Split_Cat").ToString
Dim Engr_Time As String = dr("Engr_Time").ToString
Dim PLANDESC As String = dr("PLANDESC").ToString
Dim STEPSEQ As String = dr("STEPSEQ").ToString
Dim EQPTYPE As String = dr("EQPTYPE").ToString
Dim PPID As String = dr("PPID").ToString
Dim STEPDESC As String = dr("STEPDESC").ToString
Dim Split As String = dr("Split").ToString
Dim Recipe As String = dr("Recipe").ToString
Dim a As String = dr("F11").ToString
Dim b As String = dr("F12").ToString
Dim c As String = dr("F13").ToString
.............
Dim insertsql2 As String = ""
insertsql2 += "insert into PTHOME.dbo.SplitTable (LotID,Split_Cat,Engr_Time,PLANDESC,STEPSEQ,EQPTYPE,PPID,STEPDESC,Split,Recipe,[1],[2],[3]) values "
insertsql2 += "('" + LotID + "','" + Split_Cat + "','" + Engr_Time + "','" + PLANDESC + "','" + STEPSEQ + "','" + EQPTYPE + "','" + PPID + "','" + STEPDESC + "','" + Split + "','" + Recipe + "', "
insertsql2 += " '" + a + "','" + b + "','" + c + "') "
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(insertsql2, conn)
conn.Open()
Dim res As Integer = cmd.ExecuteNonQuery
conn.Close()
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Else
Label2.Text = " NO Records Uploaded! "
End If
Catch ex As Exception
Label2.Text = " Failed to Upload, pls check your data or file format ! "
End Try
Next
End If
End If
End Sub
When i upload the xls file, the label displayed
"Please select a File to upload!", anything i missed out in the popup control? Please guide me on this, thanks in advance.
EDIT*
I have changed the upload control to this and it no longer showed the "Please select a File to upload!" now there is another error showed "File is not in correct format - Details: F11", the error seems to lie on the column [1]-[12], but the excel column is 1-12 and the column in database is [1]-[12].how can i achieve this? ( Solved by changing the number to F11 and so on.)
<dx:ASPxUploadControl runat="server" ClientInstanceName="XXUpload" ID="XXUpload" Width="600px" >
<ValidationSettings AllowedFileExtensions=".xls"></ValidationSettings>
</dx:ASPxUploadControl>
Edit 2*
The data has uploaded successfully to sql server and now another problem occurred, the data uploaded to sql server wont show in the UpdateSplitGrid gridview although i have declared this in my code.
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Your ASPxUploadControl, the XXUpload, doesn't have any function to execute when upload is complete. I suggest you use OnFileUploadComplete event with FileUploadMode="OnPageLoad".

my code is as shown and i get this error "The remaining text does not appear to be part of the formula">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
reportdoc1.Load(Server.MapPath("~\RepVoucherchq.rpt"))
CrystalReportViewer1.ReportSource = reportdoc1
ConnectionInfo()
Dim user_brno As String = CType(Session("userBrn"), String)
Dim date_from As String = CType(Session("date_from"), String)
Dim date_to As String = CType(Session("date_to"), String)
reportdoc1.RecordSelectionFormula = "{VEWVoucherchq.vocdate} between '" + date_from + "' and '" + date_to + "' and {VEWVoucherchq.chqbrNo} = " + user_brno
CrystalReportViewer1.RefreshReport()
End Sub
I don't have Visual Studio on this computer to test this completely, but I think your syntax is off in your Record Selection Formula.
Try this instead:
reportdoc1.RecordSelectionFormula = "{VEWVoucherchq.vocdate} in '" + date_from + "' to '" + date_to + "' and {VEWVoucherchq.chqbrNo} = " + user_brno
The between/and syntax you used isn't supported in Crystal Reports for evaluating a date the way you want. The supported syntax is {eval_date} IN {start_Date} to {end_Date}.
You may also run into an issue with your date_from and date_to fields being string data types instead of the Date or DateTime datatype. If that is an issue, you will want to pass the values through a function to convert them to dates properly.
Something like this should suffice:
reportdoc1.RecordSelectionFormula = "{VEWVoucherchq.vocdate} in Date('" + date_from + "') to Date('" + date_to + "') and {VEWVoucherchq.chqbrNo} = " + user_brno
If you need DateTime instead of Date data types, replace the Date() functions with DateTime() functions.

ASP.NET (VB) Trying set DB connection from web.config

I have a web form project to update columns in an Microsoft SQL 2012 database table. When I "hard code" the connection info for my SqlConnection everything works fine. However if I try going the ConfigurationManager.ConnectionStrings route I get a keyword 'id' not supported. I have included the Imports.System.Configuration code into my project. Below is the Sub where I am running into the issue
Protected Sub BtnSubmit_Click(sender As Object, e As EventArgs) Handles BtnSubmit.Click
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring, RqType, RqLast, RqFirst, RqOrg, RqEmail, RqNeedDate, SubFirst, SubLast, RqDetails, RqGenDate, RqOperator As String
RqType = cbxRequestType.SelectedValue
RqLast = txtReqLastName.Text
RqFirst = txtReqFirstname.Text
RqOrg = txtOrganization.Text
RqEmail = txtEmail.Text
RqNeedDate = txtReqDate.Text
SubFirst = txtSubFirst.Text
SubLast = txtSubLast.Text
RqDetails = txtReqDetails.Text
RqGenDate = txtGenDate.Text
RqOperator = txtOperator.Text
If Agree.Checked = False Then
MsgBox("You must agree to the terms before proceeding")
Else
myConn = New SqlConnection(ConfigurationManager.ConnectionStrings("PRRWeb").ConnectionString)
myConn.Open()
sqlstring = "INSERT INTO Requests (LastName, FirstName, Organization, DateRequested, DateNeeded, OperatorID, SubjectLastName, SubjectFirstName, Notes, TypeID, Email) VALUES ('" + RqLast + "','" + RqFirst + "', '" + RqOrg + "','" + RqGenDate + "', '" + RqNeedDate + "','" + RqOperator + "','" + SubLast + "','" + SubFirst + "','" + RqDetails + "','" + RqType + "','" + RqEmail + "')"
cmd = New SqlCommand(sqlstring, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
MsgBox("Your request has been submitted.", MsgBoxStyle.Information)
Response.Redirect(Request.RawUrl)
End If
Resolved the issue by adding a connectionstring to my web.config like so
<connectionStrings >
<add
name="PRRWeb"
connectionString="Server=server;Database=DB;Timeout=200;User ID=user; Password=Password; Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
And then added this to my vb code
myConn = New SqlConnection(ConfigurationManager.ConnectionStrings ("PRRWeb").ConnectionString)

error in submit button

I have an error in the execution of my code. It says "Syntax error in INSERT INTO statement". This is my code:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click GridView1.Visible = True
Dim myConn As OleDbConnection
Dim sqlString, takenby, dest, client, car As String
Dim recordno As Integer
Dim dte, exptime As String
recordno = TextBox4.Text
dte = TextBox1.Text
car = ComboBox1.SelectedValue.ToString()
takenby = ComboBox2.SelectedValue.ToString
dest = ComboBox3.SelectedValue.ToString
client = TextBox2.Text
exptime = TextBox3.Text
myConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\student\WebSite3\App_Data\Database.mdb;Persist Security Info=False;")
myConn.Open()
sqlString = "INSERT INTO DETAILED GISTEC CARS(Record No, Date, Car, Taken By, Destination, Client, Expected Time to Return)VALUES(?recordno, ?dte, ?car, ?takenby, ?dest, ?client, ?exptime);"
Dim cmd = New OleDbCommand(sqlString, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
End Sub
You should change your query to use question mark placeholders and then add paramters to prevent (amongst other things) sql injection issues.
You also need to add square brackets to your column names if they have spaces in them:
sqlString = "INSERT INTO [DETAILED GISTEC CARS] ([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES (?, ?, ?, ?, ?, ?, ?);"
Dim cmd = New OleDbCommand(sqlString, myConn)
cmd.Parameters.Add(New OleDbParameter("Record No", recordno))
cmd.Parameters.Add(New OleDbParameter("Date", dte))
'etc
'etc
cmd.ExecuteNonQuery()
See this page about OleDbParameters for more information.
Try to execute query directly in Access until it works.
From here it looks like
You have no spaces around VALUES
Your table name contain spaces so better use [] to surround table name
Same with some column names.
Not sure of ?recordno syntax in vb so better use + operator
sqlString = "INSERT INTO [DETAILED GISTEC CARS]([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES (" + recordno + ", " + dte + ", " + car +", " + takenby, " + dest + ", " + client + ", " + exptime + ");"
An alternative to cad's concatenation method would be to use curly brace array placeholders. Something like this should do it:
sqlString = String.Format("INSERT INTO [DETAILED GISTEC CARS] ([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6});", recordno, dte, car, takenby, dest, client, exptime)
You should also put single quotes around non-numeric values, escape any user entered single quotes, and call the Access CDATE function for Date/Time columns. So, assuming dte is user entered data and exptime is a Date\Time column, those two variables might be set like this:
dte = "'" + TextBox1.Text.Replace("'", "''") + "'"
exptime = "CDATE('" + TextBox3.Text + "')"
and so on and so forth...

Resources