I'm using this code to insert in database , but every time it inserts more than one row ,what is the problem ?
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Sub
Have you checked to see if your block of code is being called more than once? One quick way is to put a alert box inside so you can count the times it runs.
Well... there are lots of problems. The first of which is the potential for SQL Injection, you should be using named parameters. Another is that the line about Dim com As New... should also be in a Using clause.
However, nothing in that bit of code suggests that it is inserting more than 1 record. I suggest you put a break point on the ExecuteNonQuery line and see what's going on.
I have checked and hole the button click was executed twice , I have changed the code to this one and it has been solved , but I dont know why the click event is executed twice :
Dim i As Boolean = True
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
con.Open()
Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
If i = True Then
com.ExecuteScalar()
i = False
End If
End Using
con.Close()
End Using
End Sub
Related
I'm doing insert username and password into database in vb.net but it gives this error:
the error image
can someone take a look what cause it?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Amin\source\repos\Nando's\Nando's\user.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
MsgBox("Record added", MsgBoxStyle.Information)
End Sub
I change from this:
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
to this:
command = "insert into [user] ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
I just put a bracket at user and it is solved.
The bad thing is I was going back and forth between tutorial for days but neither of them solve it because the error was on the table name but it is finally solved. Thank you to Hursey for mentioning reserved words.
i'm gonna straight forward. i have these lines of codes. basically it's about update data based on user input. but first, the textbox will retrieve data from database, and then the user will be free to change the value/text of the textbox and when the user click a button, the system will store the new value to database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim check As String = Session("user_id")
Dim SqlSelect As String = "SELECT * FROM Worker Where user_id='" & check & "' "
Dim con As dbConn = New dbConn()
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Try
con.open()
reader = cmd.ExecuteReader()
reader.Read()
WorkerID_.Text = reader("WorkerID").ToString()
WorkerName.Text = reader("WorkerName").ToString()
DoB.Text = reader("DoB").ToString()
Address.Text = reader("Address").ToString()
Phone.Text = reader("Phone").ToString()
Email.Text = reader("Email").ToString()
Company.Text = reader("CompanyName").ToString()
PassNum.Text = reader("PassportNum").ToString()
PassExp.Text = reader("PassportExp").ToString()
VisaExp.Text = reader("VisaExp").ToString()
Finally
reader.Close()
con.close()
End Try
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs)
Dim con As dbConn = New dbConn()
Dim SqlUpdate As String
SqlUpdate = "UPDATE Worker SET "
SqlUpdate &= "WorkerID = '" & WorkerID_.Text & "', "
SqlUpdate &= "WorkerName = '" & WorkerName.Text & "', "
SqlUpdate &= "Address = '" & Address.Text & "', "
SqlUpdate &= "Email = '" & Email.Text & "', "
SqlUpdate &= "CompanyName = '" & Company.Text & "', "
SqlUpdate &= "PassportNum = '" & PassNum.Text & "' "
SqlUpdate &= "Where user_id ='" & Session("user_id") & "'"
Dim cmd As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim rad As OleDbDataReader
Try
con.open()
rad = cmd.ExecuteReader()
Finally
rad.Close()
con.close()
Response.Redirect("~\Worker\Profile.aspx")
End Try
End Sub
based on this code, the data can't be updated. the textbox.text in update_click will retrieve the same value of textbox in page_load (which is data from database) instead of the text input by the user.
it all worked fine if i delete the code for retrieving the data from database inside page_load. did i miss something in my code?
put
If Not Page.IsPostBack Then
//code
End If
inside page_load
Good day All
i have an issue with connection string
I'm getting this exception
The ConnectionString property has not been initialized.
on the RowDataBound of the outer gridview sub routine (VB.NET)
when trying to bind data to inner gridview
the code:
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As SqlDataSource
Dim strQRY As String = ""
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
strQRY = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
'Initialize command object
Dim cmd As New SqlCommand(strQRY, conn)
Dim dsTemp As New SqlDataSource()
dsTemp.SelectCommand = strQRY
Return dsTemp
End Using
End Function
This event occurs for each row
Protected Sub gvOdv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
'Find Child GridView control
Dim gv As New GridView()
gv = DirectCast(row.FindControl("gvSorties"), GridView)
'Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
If gv.UniqueID = gvUniqueID Then
gv.PageIndex = gvNewPageIndex
gv.EditIndex = gvEditIndex
'Check if Sorting used
If gvSortExpr <> String.Empty Then
GetSortDirection()
strSort = " ORDER BY " & String.Format("{0} {1}", gvSortExpr, gvSortDir)
End If
'Expand the Child grid
ClientScript.RegisterStartupScript([GetType](), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" & DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString() & "','one');</script>")
End If
'Prepare the query for Child GridView by passing the Odv ID of the parent row
gv.DataSource = ChildDataSource(DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString(), strSort)
gv.DataBind()
'Add delete confirmation message for Customer
Dim l As LinkButton = DirectCast(e.Row.FindControl("linkDeleteCust"), LinkButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this Customer " & DataBinder.Eval(e.Row.DataItem, "OdvID") & "')")
End Sub
thanks (I'v been hunting this error for last 3 hours)
It looks like both code snippets use a separate connection string. ChildDataSource uses "SiteConnectionString" and gvOdv_RowDataBound uses "MoyensAeriensConnectionString", hopefully I'm not pointing out the obvious here, but if so, are both of those present in your config file?
When you have created the SqlDataSource dynamically in your first code snippet, You haven't set its ConnectionString property, that's why this error is coming up.
Note that you also haven't assigned any ID to your SqlDataSource. Its better to do this too.
You also need to set the ConnectionString property of SqlDataSource.
Dim dsTemp As New SqlDataSource()
dsTemp.ID = "mySqlSourceControl"
dsTemp.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionStr").ConnectionString
dsTemp.SelectCommand = strQRY
...
Rest of things should also be fine like: web.config has a connection string for the key mentioned [ e.g. ConnectionStr here]
Instead of returning a SQLDataSource as the gridview's datasource, perhaps return a dataset.
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As DataSet
Dim strQRY As String = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
Using da As New SqlDataAdapter(strQRY, conn)
Using ds As New DataSet
If da.Fill(ds) > 0 Then
Return ds
Else
Return New DataSet
End If
End Using
End Using
End Using
End Function
The method to set the datasource of the child gridview remains the same.
I am a newbie in using asp.net, I am getting a problem on how to refresh the GridView after the data is updated but it seems it's not working on my others pages. I have same code when I updated the supplier info and then the GridView1.Databind() is working but when I try to use this again on my other pages it doesn't work. Can you give an idea why is this happens?
Here is my code:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "UPDATE ProductTable SET ProductCode = ('" & lbl_productcode.Text & "'), ProductName = ('" & txt_prodname.Text & "'),ProductCategory =('" & lbl_category.Text & "'),Price =('" & txt_price.Text & "'), Quantity=('" & txt_qty.Text & "'), CategoryID=('" & lbl_catid.Text & "') WHERE ProductCategory = '" & TextBox1.Text & "'"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("RECORD UPDATED", MsgBoxStyle.Information)
GridView1.DataBind()
Call clear()
End Sub
I do not see anywhere in your code where you actually set the DataSource of your GridView before you DataBind() it. Check it out!
UPDATE:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "UPDATE ProductTable SET ProductCode = ('" & lbl_productcode.Text & "'), ProductName = ('" & txt_prodname.Text & "'),ProductCategory =('" & lbl_category.Text & "'),Price =('" & txt_price.Text & "'), Quantity=('" & txt_qty.Text & "'), CategoryID=('" & lbl_catid.Text & "') WHERE ProductCategory = '" & TextBox1.Text & "'"
cmd.Connection.Open()
Me.GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
cmd.Connection.Close()
MsgBox("RECORD UPDATED", MsgBoxStyle.Information)
Call clear()
End Sub
Good luck!
this code works fine but its inserts the same data twice in sql db on just one button click . if i made some mistake plz let me know ..
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim str As String
str = "insert into cmember(name,period,design,duty,quali,cont)values ('" & TextBox1.Text & "', '" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "', '" & TextBox5.Text & "','" & TextBox6.Text & "')"
If con.State = ConnectionState.Closed Then
con.Open()
End If
Try
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = str
Catch ex As Exception
MsgBox(e.ToString)
End Try
If cmd.ExecuteNonQuery Then
Label1.Text = "entry saved"
con.Close()
Else
Label1.Text = "entry not saved"
End If
End Sub
I can't see the valid reason why it inserts twice a same record in current code snippet. May be a button is hit twice or you are refreshing a web page.
Off-the topic : Do not use hard coded SQL statement. Use parameterized query. (Read about SQL Injection)
str = "insert into cmember (name,period,design,duty,quali,cont) values
(#name,#period,#design,#duty,#quali,#cont)"
This might seem silly, but you're not double clicking the button, are you ?
Also, never use a Msgbox call in ASP - the messagebox will appear on the server, not on the browser, and it will block the thread until clicked. You're much better to create an ASP Label control and assign the text to that.
Also, the bit enclosed in a Try block is just settings and will never throw an error - the try block should be around the commands where you open the connection, and where you execute the query.
Your code is not appearing to insert this data in twice.
The best way to find out what exactly is happening is to run a trace through SQL Server Profiler. To do this you need to ensure you have ALTER TRACE permissions on the instance.