Database not updating after UPDATE SQL statement in ASP.net - asp.net

I currently have a problem attepting to update a record within my database. I have a webpage that displays in text boxes a users details, these details are taken from the session upon login. The aim is to update the details when the user overwrites the current text in the text boxes.
I have a function that runs when the user clicks the 'Save Details' button and it appears to work, as i have tested for number of rows affected and it outputs 1. However, when checking the database, the record has not been updated and I am unsure as to why.
I've have checked the SQL statement that is being processed by displaying it as a label and it looks as so:
UPDATE [users]
SET [email] = #email,
[firstname] = #firstname,
[lastname] = #lastname,
[promo] = #promo
WHERE [users].[user_id] = 16
The function and other relevant code is:
Sub Page_Load(sender As Object, e As EventArgs)
usernameLabel.text = session.contents.item("UserName")
if usernameLabel.text = "" then
logoutButton.Visible = False
loggedInAsLabel.Visible = False
else
labelGuest.Visible = False
linkLogin.Visible = False
linkRegister.Visible = False
end if
emailBox.text = session.contents.item("Email")
firstBox.text = session.contents.item("FirstName")
lastBox.text = session.contents.item("LastName")
promoBox.text = session.contents.item("Promo")
End Sub
Sub Button1_Click(sender As Object, e As EventArgs)
changeDetails(emailBox.text, firstBox.text, lastBox.text, promoBox.text)
End Sub
Function changeDetails(ByVal email As String, ByVal firstname As String, ByVal lastname As String, ByVal promo As String) As Integer
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\Documents an"& _
"d Settings\Paul Jarratt\My Documents\ticketoffice\datab\ticketoffice.mdb"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)
Dim queryString As String = "UPDATE [users] SET [email]=#email, [firstname]=#firstname, [lastname]=#lastname, "& _
"[promo]=#promo WHERE ([users].[user_id] = " + session.contents.item("ID") + ")"
Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dbParam_email As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_email.ParameterName = "#email"
dbParam_email.Value = email
dbParam_email.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_email)
Dim dbParam_firstname As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_firstname.ParameterName = "#firstname"
dbParam_firstname.Value = firstname
dbParam_firstname.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_firstname)
Dim dbParam_lastname As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_lastname.ParameterName = "#lastname"
dbParam_lastname.Value = lastname
dbParam_lastname.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_lastname)
Dim dbParam_promo As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_promo.ParameterName = "#promo"
dbParam_promo.Value = promo
dbParam_promo.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_promo)
Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try
labelTest.text = rowsAffected.ToString()
if rowsAffected = 1 then
labelSuccess.text = "* Your details have been updated and saved"
else
labelError.text = "* Your details could not be updated"
end if
End Function
Any help would be greatly appreciated.

Does your page have a RequiresTransaction property? If so, check that there are no exceptions thrown elsewhere during the request which might cause the transaction to roll back - leaving the data unchanged.

Are you sure that you're updating the database you think you're updating? I don't like the look of that connection string at all (and, frankly, I doubt Paul Jarratt would be too happy to see it posted here).

Related

PDFs missing EOF section on customer's server

Folks- I'm relatively new to ASP.NET, and have a question that has stumped my peers-- folks much more experienced than myself.
My company created a website that uses iTextSharp to build and stream PDFs. The functionality works perfectly on my company's development and staging/test servers. The customer's functionality isn't working well, however. The customer's server streams a file where the PDF is missing the last block of data representing the EOF section. The PDF seems to build correctly, streams correctly, but when users open the PDF, the following error displays: 'There was an error opening this document. The file is damaged and could not be repaired.'
By comparing the PDFs in a text viewer (comparing the PDFs from my server vice the customer's server), I can see that the EOF section is missing from the customer's PDF. I'll also note that no errors are thrown during PDF creation, if that's helpful. To make matters more difficult, I have no access to the customer's servers, so I won't be able to interact with the systems directly.
The asp.net version is 3.5. Both of our servers (my company and the customer) are: running IIS7.5 on Server 2008R2; using iTextSharp is 5.1.2; and are configured for FIPS compatibility.
I've read dozens and dozens of posts detailing why a PDF isn't created properly, why it may not be streaming, and all things related, but I haven't seen this particular issue before. I guess what I need to know in the short-term is: 1) what can I provide to help diagnose the issue, 2) where is a good place to start looking for areas of concern?
Also, I updated to revision 5.5.3 last night; same results-- it works fine on my servers, but produces broken PDFs on the customer's server.
Code added:
Public Function BuildReport(ByVal tblReport As DataTable, _
ByRef memStream As MemoryStream, _
ByRef strErrMsg As String) As Boolean
Dim booOK As Boolean = True
strErrMsg = String.Empty
' Create document
Try
' Create writer (listens to the document and directs PDF stream)
memStream = New MemoryStream()
Dim msWriter As PdfWriter = PdfWriter.GetInstance(_document, memStream)
msWriter.CloseStream = False
'Create header
Dim ev As New itsEvents
msWriter.PageEvent = ev
' Set document metadata
_document.AddTitle(_strMetaTitle)
_document.AddSubject(_strMetaSubject)
_document.AddCreator(_strMetaApplication)
_document.AddAuthor(_strMetaAuthor)
' Open document, add document content, close document
_document.Open()
AddReportContent(tblReport)
_document.Close()
Catch ex As Exception
booOK = False
strErrMsg = ex.Message
End Try
Return booOK
End Function
Private Sub AddReportContent(ByVal tblReport As DataTable)
' Count report columns
Dim intReportColumns As Integer = 0
For Each col As DataColumn In tblReport.Columns
If ContainedInColumnMask(col.ColumnName) Then
intReportColumns += 1
End If
Next
' Build table
Dim table As PdfPTable
Dim cell As PdfPCell
Dim phrase As Phrase
If intReportColumns >= 1 Then
' Init table
table = New PdfPTable(intReportColumns)
' Add title to table
'phrase = New Phrase(_strMetaTitle, _fontLarge)
'cell = New PdfPCell(phrase)
'cell.Colspan = intReportColumns
'cell.HorizontalAlignment = 1 ' 0=Left, 1=Centre, 2=Right
'table.AddCell(cell)
' Add column headers to table
Dim i As Integer = 0
Dim intColWidth As Integer
Dim intColWidths As Integer() = New Integer(intReportColumns - 1) {}
Dim intColWidthTotal As Integer = 0
Dim strColName As String
For Each col As DataColumn In tblReport.Columns
If ContainedInColumnMask(col.ColumnName) Then
strColName = col.ColumnName
If (col.ExtendedProperties.Item("NOTEXTEXPORT") <> True) Then
If col.ExtendedProperties.Contains("FRIENDLYNAME") Then
strColName = col.ExtendedProperties.Item("FRIENDLYNAME")
End If
End If
phrase = New Phrase(strColName, _fontMedium)
cell = New PdfPCell(phrase)
cell.BorderWidth = 1
cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
'cell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY
table.AddCell(cell)
intColWidth = GetColumnWidth(col, strColName, _fontMedium.Size, _fontSmall.Size)
intColWidths(i) = intColWidth
intColWidthTotal += intColWidth
i += 1
End If
Next
table.TotalWidth = intColWidthTotal
table.SetWidths(intColWidths)
' Add rows to table
For Each row As DataRow In tblReport.Rows
For Each col As DataColumn In tblReport.Columns
If ContainedInColumnMask(col.ColumnName) Then
phrase = New Phrase(SetBlankIfNothing(row.Item(col.ColumnName).ToString()), _fontSmall)
cell = New PdfPCell(phrase)
cell.BorderWidth = 0.5
table.AddCell(cell)
End If
Next
Next
Else
' Init table
table = New PdfPTable(1)
' Nothing to add to table
table.AddCell(String.Empty)
End If
' Add table to document
_document.Add(table)
End Sub
Public Sub New(ByVal strMetaTitle As String, _
ByVal strMetaSubject As String, _
ByVal strMetaApplication As String, _
ByVal strMetaAuthor As String, _
Optional ByVal strColumnMask As String = "")
GetStaticInfo()
_strMetaTitle = strMetaTitle
_strMetaSubject = strMetaSubject
_strMetaApplication = strMetaApplication
_strMetaAuthor = strMetaAuthor
_document = New iTextSharp.text.Document(_itsPage, _itsMarginLeft, _itsMarginRight, _itsMarginTop, _itsMarginBottom)
If strColumnMask <> "" And Not strColumnMask Is Nothing Then
_strColumnMask = strColumnMask
End If
End Sub
Public Sub New(ByVal strMetaTitle As String, _
ByVal strMetaSubject As String, _
ByVal strMetaApplication As String, _
ByVal strMetaAuthor As String, _
Optional ByVal strColumnMask As String = "")
GetStaticInfo()
_strMetaTitle = strMetaTitle
_strMetaSubject = strMetaSubject
_strMetaApplication = strMetaApplication
_strMetaAuthor = strMetaAuthor
_document = New iTextSharp.text.Document(_itsPage, _itsMarginLeft, _itsMarginRight, _itsMarginTop, _itsMarginBottom)
If strColumnMask <> "" And Not strColumnMask Is Nothing Then
_strColumnMask = strColumnMask
End If
End Sub

Check if Record Exists IN DB Using ASP VB

I am trying to check whether an email exists in my sql database from an an asp code behind
Basically a user will fill in a form and submit, I need to check wther that email exists first before inserting
Protected Sub btnSignup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSignup.Click
Response.Cookies("survey")("fullname") = TextBoxFullName.Text
Response.Cookies("survey")("surname") = TextBoxSurname.Text
Response.Cookies("survey")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("survey")("contactnumber") = TextBoxPhone.Text
Response.Cookies("survey")("email") = TextBoxEmail.Text
Response.Cookies("survey").Expires = DateTime.Now.AddDays(365)
'InsertCommand="INSERT INTO [Comp_20140409_Broadband] ([SignupName], [SignupGender], [SignupIDNo], [SignupEmailAddress], [CurrentProvider], [CurrentSpeed], [CurrentUsage]) VALUES (#SignupName, #SignupGender, #SignupIDNo, #SignupEmailAddress, #CurrentProvider, #CurrentSpeed, #CurrentUsage)"
If Not Page.IsValid Then Exit Sub
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql3 As String = "Select [PersonId] FROM [Users] WHERE [Email] = #Email"
Dim PersonId As Integer
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql3, myConnection)
myCommand.Parameters.AddWithValue("#Email", TextBoxEmail.Text)
PersonId = myCommand.ExecuteScalar()
myConnection.Close()
End Using
Dim updateSql2 As String = " INSERT INTO [Survey_Legal] ([LegalInsurance],[ThirdParty], [LegalIssues], [RequestLegal], [PersonId], [Category_Type]) VALUES (#LegalInsurance, #ThirdParty, #LegalIssues, #RequestLegal, #PersonId, #Type )"
Using myConnection2 As New SqlConnection(connectionString)
myConnection2.Open()
Dim myCommand2 As New SqlCommand(updateSql2, myConnection2)
myCommand2.Parameters.AddWithValue("#LegalInsurance", DDLLegal1.SelectedValue)
myCommand2.Parameters.AddWithValue("#ThirdParty", DDLLegal2.SelectedValue)
myCommand2.Parameters.AddWithValue("#LegalIssues", DDLLegal3.SelectedValue)
myCommand2.Parameters.AddWithValue("#RequestLegal", DDLLegal4.SelectedValue)
myCommand2.Parameters.AddWithValue("#PersonId", PersonId)
myCommand2.Parameters.AddWithValue("#Type", "Legal-Insurance")
myCommand2.ExecuteNonQuery()
myConnection2.Close()
End Using
This is how I do this. I check for a duplicate email address in my stored procedure with an output parameter.
CREATE Procedure sp_AddSubscriber
#Name as nvarchar(50),
#Email as nvarchar(50),
#AddSubscriber bit OUTPUT
AS
IF (SELECT COUNT(Email)
FROM TSubscribers
WHERE Email = #Email) = 0
BEGIN
INSERT TSubscribers (Name, Email)
VALUES (#Name, #Email)
SET #AddSubscriber = False
END
ELSE
SET #AddSubscriber = True
GO

ASP.NET VB.NET -- SQL UPDATE Command Not Working

I have been working on this particular issue for a couple of days, and scouring over SO, MSDN and other google searches has not proven to be of any use. I am trying to make a simple update to a SQL table. My SELECT and INSERT statements all work fine, but for some reason, this update will not work. I have set breakpoints and stepped through, and the code seems to be working fine -- the Catch ex as Exception is never reached after the .ExecuteNonQuery() fires off.
Could anyone give me an idea of why I've been unable to get a SQL update?
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim currentUser = Membership.GetUser(User.Identity.Name)
Dim username As String = currentUser.UserName
Dim userId As Guid = currentUser.ProviderUserKey
UserNameTextBox.Text = username
' Get Root Web Config Connection String so you don't have to encrypt it
Dim rootWebConfig As System.Configuration.Configuration
rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")
Dim connString As System.Configuration.ConnectionStringSettings
connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalSqlServer")
Dim conn As String = connString.ToString
Dim commandString As String = "UPDATE UserDetails SET FirstName ='" + FirstNameTextBox.Text + "' WHERE UserId ='" + userId.ToString + "'"
Dim fname As String = FirstNameTextBox.Text
Dim commandText As String = "UPDATE UserDetails SET FirstName=#firstname WHERE UserId=#UID;"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(commandText, connection)
command.CommandType = CommandType.Text
' Add UserId parameter for WHERE clause.
command.Parameters.Add("#UID", SqlDbType.UniqueIdentifier).Value = userId
' command.Parameters("#UID").Value = userId
' command.Parameters.AddWithValue("#UID", userId)
' Use AddWithValue to assign Demographics.
command.Parameters.Add("#firstname", SqlDbType.VarChar, 255).Value = fname
'command.Parameters.AddWithValue("#firstname", fname)
' command.Parameters("#firstname").Value = FirstNameTextBox.Text.ToString
Try
connection.Open()
command.ExecuteNonQuery()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
You're running "command.ExecuteNonQuery()" twice, meaning the second execution will likely return 0 rows affected since you already updated what you needed to update, and that's what you're assigning to rowsAffected. Are you sure the UPDATE isn't occurring?
Edit: Re your comment, did you check for IsPostBack when you LoadUser? If not, when you click SaveButton, you're going to reload the existing values, and then you'll be updating with those existing values.

Get Data from One Table and Insert to Another Via Form Submission

How do I get a UserID from one database table (Users) to be inserted into another table (Ticket)? Both columns in each table has the same datatype (int). Please take a look:
Users
UserID
UserName
Password
FirstName
LastName
Email
Updated
Deleted
Ticket
TicketID
DateCreated
UserIDNum FK
FullName
Email
Subject
Message
Deleted
These are all of the codes involved:
Partial Public Class mysupport
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
MaintainScrollPositionOnPostBack = True
SetFocus(helpTopicDDL)
Else
SetFocus(fullNameTXTBOX)
End If
Dim sConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TrackTicketsConnectionString2").ConnectionString)
sConnection.Open()
If Session("Ticket") Is Nothing Then
Response.Redirect("SignIn.aspx")
Else
Dim cmdS As String = "Select * from Users Where Deleted='N' AND Username=#Username"
Dim cmdCheckEmail As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#Username", Data.SqlDbType.VarChar)
cmdCheckEmail.Parameters.Add("#Username", SqlDbType.VarChar)
cmdCheckEmail.Parameters.Item("#Username").Value = Session("Ticket")
Dim obj As Object = cmdCheckEmail.ExecuteScalar()
If obj IsNot Nothing Then
mailLBL.Text = Convert.ToString(obj)
End If
End If
sConnection.Close()
End Sub
Protected Sub submitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitBTN.Click
Dim sdConnection As String = ConfigurationManager.AppSettings("TrackTicketsConnectionString2")
Dim iRowCount As Integer
Dim cmdInsertTicket As New Data.SqlClient.SqlCommand
Dim conticket As New Data.SqlClient.SqlConnection
conticket.ConnectionString = sdConnection
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "Insert Into Ticket " _
& "( DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values( #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
'Dim appUserName As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.NVarChar)
'cmdInsertTicket.Parameters.Add(appUserName)
'cmdInsertTicket.Parameters.Item("#UserName").Value = User.Identity.Name
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
Dim appFullName As New Data.SqlClient.SqlParameter("#FullName", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appFullName)
cmdInsertTicket.Parameters.Item("#FullName").Value = fullNameTXTBOX.Text
Dim appEmail As New Data.SqlClient.SqlParameter("#Email", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appEmail)
cmdInsertTicket.Parameters.Item("#Email").Value = emailAddTXTBOX.Text
Dim appTicketType As New Data.SqlClient.SqlParameter("#TicketType", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appTicketType)
cmdInsertTicket.Parameters.Item("#TicketType").Value = helpTopicDDL.SelectedValue
Dim appSubject As New Data.SqlClient.SqlParameter("#Subject", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appSubject)
cmdInsertTicket.Parameters.Item("#Subject").Value = subjectTXTBOX.Text
Dim appMessage As New Data.SqlClient.SqlParameter("#Message", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appMessage)
cmdInsertTicket.Parameters.Item("#Message").Value = messageTXTBOX.Text
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
conticket.Open()
Try
iRowCount = cmdInsertTicket.ExecuteScalar()
statusLBL.Text = "Ticket has been submitted successfully."
Catch
statusLBL.Text = "Ticket has not been submitted. Please try again."
End Try
conticket.Close()
End Sub
What I really wanted is for a person's UserID to be stored in Ticket table after he has logged in to fill out a form and submitted it. I'm at a loss in how to pull the data from Users table to insert into Ticket table. Any help is much appreciated as I'm still learning.
EDIT:
Inserting the UserID into the Tickets table when adding a record first requires that you have access to the UserID value. You then need to pass this value in your INSERT statement.
Looks like we first need to retrieve the UserId. Since you are using FormsAuthentication we can retrieve the UserName from the User.Identity.Name object and use that as the value in our first query to retrieve the UserId.
Dim cmdS As String = "Select [UserID] from Users Where Deleted='N' AND UserName=#UserName"
Dim cmdGetUserId As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.VarChar)
cmdGetUserId.Parameters.Add("#UserName", SqlDbType.VarChar)
cmdGetUserId.Parameters.Item("#UserName").Value = User.Identity.Name
Dim obj As Object = cmdGetUserId.ExecuteScalar
Dim myUserId As Integer = Integer.Parse(obj)
Now that we have the UserId value for our current user we can modify our INSERT statement and parameters.
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "INSERT INTO Ticket " _
& "(UserID, DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values(#UserID, #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
Dim appUserId As New Data.SqlClient.SqlParameter("#UserID", Data.SqlDbType.Int)
cmdInsertTicket.Parameters.Add(appUserId)
cmdInsertTicket.Parameters.Item("#UserID").Value = myUserId
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
...
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
You can access authentication information through the User.Identity object once the user has been authenticated. Might also want to think about implementing a custom IIdentity class to store the UserID if you will need access to it often. Here's a good MSDN article about Custom Authentication: http://msdn.microsoft.com/en-us/library/ms172766(v=vs.80).aspx
UPDATE:
In regards to the comment below, you are retrieving the UserID because the SqlCommand is being executed with the ExecuteScalar method which returns the value of the first column of the first row. I would recommend taking a closer look at the SqlCommand object: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx and this ADO.NET primer on MSDN: http://msdn.microsoft.com/en-us/library/e80y5yhx(v=vs.80).aspx

ASP Net UPDATE Command not working

I have the following UPDATE command (written in VB) in my code.
Dim currentUser As String = User.Identity.Name
Dim myConnectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
Dim myCommand As New SqlCommand("UPDATE tblProfile SET Title= #Title, FirstName= #FirstName, LastName= #LastName, MiddleName= #MiddleName, HomePhoneNumber= #HomePhoneNumber, MobilePhoneNumber= #MobilePhoneNumber, Address= #Address, StreetName= #StreetName, StreetType= #StreetType, Suburb= #Suburb, PostCode= #PostCode, State= #State WHERE UserName = '" & currentUser & "'", New SqlConnection(myConnectionString))
myCommand.Connection.Open()
myCommand.Parameters.AddWithValue("#Title", Title.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#FirstName", FirstName.Text)
myCommand.Parameters.AddWithValue("#LastName", LastName.Text)
If MiddleNames.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MiddleName", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MiddleName", MiddleNames.Text)
End If
If HomePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#HomePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#HomePhoneNumber", HomePhoneNumber.Text)
End If
If MobilePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", MobilePhoneNumber.Text)
End If
myCommand.Parameters.AddWithValue("#Address", AddressNumber.Text)
myCommand.Parameters.AddWithValue("#StreetName", StreetName.Text)
myCommand.Parameters.AddWithValue("#StreetType", StreetType.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#Suburb", Suburb.Text)
myCommand.Parameters.AddWithValue("#PostCode", Postcode.Text)
myCommand.Parameters.AddWithValue("#State", State.SelectedItem.Text)
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
Dim myCommandPref As New SqlCommand("UPDATE tblPreferences SET Classical = #Classical, Comedy = #Comedy, Concerts = #Concerts, Dance = #Dance, DiningOut = #DiningOut, Exhibitions = #Exhibitions, Family = #Family, Festivals = #Festivals, Lifestyle = #Lifestyle, Musicals = #Musicals, Opera = #Opera, Rock = #Rock, Sports = #Sports, Theatre = #Theatre WHERE UserName = '" & currentUser & "'", New SqlConnection(myConnectionString))
myCommandPref.Connection.Open()
Dim boolClassical As Boolean = Preferences.Items(0).Selected
myCommandPref.Parameters.AddWithValue("#Classical", boolClassical.ToString)
Dim boolComedy As Boolean = Preferences1.Items(0).Selected
myCommandPref.Parameters.AddWithValue("#Comedy", boolComedy.ToString)
Dim boolConcerts As Boolean = Preferences.Items(1).Selected
myCommandPref.Parameters.AddWithValue("#Concerts", boolConcerts.ToString)
Dim boolDance As Boolean = Preferences1.Items(1).Selected
myCommandPref.Parameters.AddWithValue("#Dance", boolDance.ToString)
Dim boolDiningOut As Boolean = Preferences.Items(2).Selected
myCommandPref.Parameters.AddWithValue("#DiningOut", boolDiningOut.ToString)
Dim boolExhibitions As Boolean = Preferences1.Items(2).Selected
myCommandPref.Parameters.AddWithValue("#Exhibitions", boolExhibitions.ToString)
Dim boolFamily As Boolean = Preferences.Items(3).Selected
myCommandPref.Parameters.AddWithValue("#Family", boolFamily.ToString)
Dim boolFestivals As Boolean = Preferences1.Items(3).Selected
myCommandPref.Parameters.AddWithValue("#Festivals", boolFestivals.ToString)
Dim boolLifestyle As Boolean = Preferences.Items(4).Selected
myCommandPref.Parameters.AddWithValue("#Lifestyle", boolLifestyle.ToString)
Dim boolMusicals As Boolean = Preferences1.Items(4).Selected
myCommandPref.Parameters.AddWithValue("#Musicals", boolMusicals.ToString)
Dim boolOpera As Boolean = Preferences.Items(5).Selected
myCommandPref.Parameters.AddWithValue("#Opera", boolOpera.ToString)
Dim boolRock As Boolean = Preferences1.Items(5).Selected
myCommandPref.Parameters.AddWithValue("#Rock", boolRock.ToString)
Dim boolSports As Boolean = Preferences.Items(6).Selected
myCommandPref.Parameters.AddWithValue("#Sports", boolSports.ToString)
Dim boolTheatre As Boolean = Preferences1.Items(6).Selected
myCommandPref.Parameters.AddWithValue("#Theatre", boolTheatre.ToString)
myCommandPref.ExecuteNonQuery()
myCommandPref.Connection.Close()
When the user presses the button which fires that code, my page simply refreshes, but does not update the information in the database. I have looked around, and some people were saying you needed to have the primary key as the 'where' statement, so I made 'UserName' the primary key in both tables.
Could someone please help me to fix this.
I went back to my code after a few months today, and after a brief search through, found the problem... I needed to include 'if not IsPostBack then...' to my Page_Load. I was resetting my page each time the button was pressed, which reset the fields on my page, thus sending the same information back to my server - I was updating my server with the same information.
For anyone with the same problem, this helped me:
http://www.java-samples.com/showtutorial.php?tutorialid=1083

Resources