I'm a VB.NET programmer. I have created an update web form in ASP.NET having 3 fields; ID, Names, Email with 3 buttons cmdUpdate, cmdDelete and cmdCancel. All are executing except for the update button which is not executing, and I can't get an error message either. The code is below.
Protected Sub cmdUpdate_Click(sender As Object, e As EventArgs) Handles cmdUpdate.Click
Dim conn As New SqlClient.SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=RegDb_backend;Integrated security=true;")
Dim sql As String = "UPDATE tblClients SET ClientNames=#Names, ClientEmail=#Email WHERE ClientID=#ID;"
Dim cmd = New SqlClient.SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter("#Names", txtNames.Text.Trim()))
cmd.Parameters.Add(New SqlParameter("#Email", txtEmail.Text.Trim()))
cmd.Parameters.Add(New SqlParameter("#ID", Convert.ToInt64(txtID.Text.Trim)))
Try
conn.Open()
cmd.ExecuteNonQuery()
lblSuccess.Visible = True
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have tried researching and tweaking around with the code but the database won't get updated. Please help. Thank you.
Related
i have tried using this code, but it doesn't work,
it displays this error Error Updating DataObject reference not set to an instance of an object.
when i try updating, please see what i have done wrong here
thanks
Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim connString As String
connString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\user\Documents\Visual Studio 2010\WebSites\boomwebsite\App_Data\playaazaleaDatabase.mdf;Integrated Security=True;User Instance=True"
Dim cmd As SqlCommand
Dim myConnection As New Data.SqlClient.SqlConnection(connString)
Try
myConnection.Open()
cmd.CommandText = "(UPDATE members SET fname=#FNAME, lname=#LNAME, uname=#UNAME, pword=#PWORD WHERE id=#MemberID)"
cmd.Connection = myConnection
cmd.Parameters.AddWithValue("#MemberID", txtboxID.Text)
cmd.Parameters.AddWithValue("#FNAME", txtboxFname.Text)
cmd.Parameters.AddWithValue("#LNAME", txtboxLname.Text)
cmd.Parameters.AddWithValue("#UNAME", txtboxUname.Text)
cmd.Parameters.AddWithValue("#PWORD", txtboxPword.Text)
cmd.ExecuteNonQuery()
Response.Redirect("adminuser.aspx")
Catch ex As Exception
lblMessage.Text = "Error Updating Data" & ex.Message
Finally
myConnection.Close()
End Try
Replace Dim cmd As SqlCommand with
Dim cmd As New SqlCommand()
I'm in ASP.NET and coding in VB.
My SQL Server DB table name TempPurchases has 3 columns:
- ItemNumber (nvarchar(10),null)
- RDC (nvarchar(2),null)
- PurchaseQTY (int,null)
The user inputs to go into the table are: ItemNumberTxtBox, DropDownList1, QuantityTxtBox
This is my code:
Protected Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
Dim CON As New SqlConnection("server=blahblah.com;database=databasename;User ID=fffffff;Password=*******;")
Dim SQL As String = "INSERT INTO TempPurchases (ItemNumber, RDC, PurchaseQTY) VALUES (#ItemNumber, #RDC, #PurchaseQTY) "
Dim CMD As New SqlCommand(SQL, CON)
CMD.Parameters.Add(New SqlParameter("#ItemNumber", SqlDbType.NVarChar, 10))
CMD.Parameters("#ItemNumber").Value = ItemNumberTxtBox.Text
CMD.Parameters.Add(New SqlParameter("#RDC", SqlDbType.NVarChar, 2))
CMD.Parameters("#RDC").Value = dropdownlist1.SelectedValue
CMD.Parameters.Add(New SqlParameter("#PurchaseQTY", SqlDbType.Int))
CMD.Parameters("#PurchaseQTY").Value = QuantityTxtBox.Text
CON.Open()
CMD.ExecuteNonQuery()
CON.Close()
End Sub
What am I doing wrong? I'm not getting an error message but nothing is getting entered into the Database table.
When I use the code below for some reason when Update is clicked, hospitaltextbox.text does not show the current value in the textbox? Just the value that was originally selected. Any idea why it is not reading what is currently in the textbox?
Dim reader As SqlDataReader = cmd.ExecuteReader()
If (reader.Read()) Then
HospitalTextBox.Text = reader(7)
FirstNameTextBox.Text = reader(9)
Session("ID") = reader(0)
End If
Protected Sub cmdUpdate_Click(sender As Object, e As EventArgs) Handles cmdUpdate.Click
Dim Test As String
Test = FirstNameTextBox.Text
Try
Dim Con As SqlConnection
Dim cmd As SqlCommand
Con = New SqlConnection
Con.ConnectionString = ""
Con.Open()
cmd = New SqlCommand
cmd.Connection = Con
cmd.CommandText = "UPDATE tbltest SET [Teaching Hospital Name] = #TeachingHospitalName, [Physician First Name] = #FirstName WHERE ID = #ID"
cmd.Parameters.Add(New SqlParameter("#ID", (Session("ID"))))
cmd.Parameters.Add(New SqlParameter("#TeachingHospitalName", HospitalTextBox.Text)) 'does not show text that was changed in the textbox?
cmd.Parameters.Add(New SqlParameter("#FirstName", Test))
cmd.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
End Try
End Sub
Check your Page_Load function.
Are you doing something on PostBack to set the textbox value to something else?
If you're binding data, make sure it's done when Not IsPostback
If Not IsPostBack
BindData()
I can't see why this is not working.
I have a dropdownlist named ddlRoomName and a SQL table named roomlist.
When i run the SQL command in SQL editor it works fine. But when I load the page the rooms do not load!
Am i missing something obvious here?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
ddlRoomName.Items.Clear()
ddlRoomName.Items.Add(New ListItem("--Select Room--", ""))
ddlRoomName.AppendDataBoundItems = True
Dim strConnString As String = ConfigurationManager.ConnectionStrings("a_cisco").ConnectionString
Dim strQuery As String = "Select * from roomlist"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
ddlRoomName.DataSource = cmd.ExecuteReader()
ddlRoomName.DataTextField = "RoomName"
ddlRoomName.DataValueField = "intRoom"
ddlRoomName.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
End If
End Sub
You are only loading them on a postback. Is it really what you want? Maybe you want:
If Not Page.IsPostBack Then
End If
(then the ViewState will keep the items in the DropDownList in a postback)
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
For Each myRow As GridViewRow In GridView3.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE * FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
Next
GridView3.DataBind()
End Sub
I'm not sure why you think that will delete everything in the table, as I'm fairly certain it will not even execute. DELETE does not require any columns or * to be specified. It should just be DELETE FROM hotels WHERE [etc, etc].
Also, you should seriously consider giving this article a read: How To: Protect From SQL Injection in ASP.NET. Especially "Step 3. Use Parameters with Dynamic SQL", which detail how you could change your code to prevent SQL injection.
I believe what you are looking for is this:
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim myRow As GridViewRow = DirectCast((System.Web.UI.Control)(sender)).NamingContainer, GridViewRow)
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
GridView3.DataBind()
End Sub
The syntax may be off I'm not too familiar with VB. As well it would be better to pass the ID of the hotel record in the e.CommandArgument thus you would not have to retrieve it from a label on the page. It is deleting all your records because you are looping through all your rows in the grid view and deleting each record.