I have a gridview which shows the details of passenger who have booked their ticket
on page load event i have following code.
Label1.Text = Session("Pid").ToString()
Dim Sql As String = "select * from Plist where Pid='" & Label1.Text & "'"
Try
con.ConnectionString = strCon
Dim cm As New SqlClient.SqlCommand(Sql, con)
con.Open()
cm.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If con.State = ConnectionState.Open Then
con.Close()
End If
End Try
I am getting this error:
System.NullReferenceException: Object reference not set to an instance of an object.
the session Session("Pid") is null, you should fill it with data before and you also should check the session:
If Session("Pid") IsNot Nothing Then
' write your code
End If
Check all your "SESSIONS" for null before using it...................
And Refer
and also IRequiresSessionState Interface
Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.
Related
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.
I receive the error
No value given for one or more required parameters
when I try to execute the following code
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim t2 = TextBox2.Text
Dim dbcmd As OleDbCommand
dbcmd = New OleDbCommand("UPDATE login1 SET height ='" + TextBox2.Text + "' WHERE username =" + str, dbcon) //This is the part where the error is ....
dbcon.Open()
dbcmd.ExecuteNonQuery()
dbcon.Close()
End Sub
End Class
I've tried making changes in this statement like using different methods with parameters...but all the code shows the same error.
Using a parameterized query is definitely the way to go, but using named parameters should be discouraged in this context because OleDbCommand objects ignore the parameter names when the CommandType is Text. They only rely on the order in which the parameters appear in the CommandText (ref: here).
Therefore, the preferred approach would be
Using dbcmd As New OleDbCommand(
"UPDATE login1 SET height=? WHERE username=?",
dbcon)
dbcmd.Parameters.AddWithValue("?", TextBox2.Text) ' height
dbcmd.Parameters.AddWithValue("?", str) ' username
dbcmd.ExecuteNonQuery()
End Using
You don't supply the user name properly at the end of the query. But that's not the only problem here. Let me edit the code a bit:
Using dbcon As New OleDbConnection(cString)
dbcon.Open()
Using dbcmd As New OleDbCommand(
"UPDATE login1 SET height = #height WHERE username = #username",
dbcon)
dbcmd.Parameters.AddWithValue("#height", TextBox2.Text)
dbcmd.Parameters.AddWithValue("#username", str)
dbcmd.ExecuteNonQuery()
End Using
End Using
NOTE: the using statement to ensure the objects are disposed property and also, do not share connections. When you need a connection, build it, open it, use it, and dispose it.
I'm trying to update a record from an Ms-Access table with VB.NET and ASP.NET. I'm getting 2 errors:
On the web page that's opened I'm getting Thread was being aborted
Web Developer 2010 gives me an error says there's an error in the
UPDATE statement
This is the code so far:
Imports System.Data.OleDb
Partial Class ChangePassword
Inherits System.Web.UI.Page
Protected Sub btnChange_Click(sender As Object, e As System.EventArgs) Handles btnChange.Click
Dim tUserID As String = Session("UserID")
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;")
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where UserID=?", conn)
Dim cmd2 = New OleDbCommand("UPDATE USER SET [Password] = '" + txtConfPass.Text + "' where UserID = '" + tUserID + "'", conn)
cmd.Parameters.AddWithValue("#UserID", tUserID)
Dim read As OleDbDataReader = cmd.ExecuteReader()
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
lblUser.Text = tUserID.ToString
lblUser.Visible = True
If read.HasRows Then
While read.Read()
If txtOldPass.Text = read.Item("Password").ToString Then
cmd2.ExecuteNonQuery()
lblPass.Visible = True
End If
End While
Else
lblPass.Text = "Invalid Password."
lblPass.Visible = True
End If
conn.Close()
lblPass.Text = tUserID.ToString
lblPass.Visible = True
Any help would be appreciated.
Thanks !
First, your cmd2 fails because USER is a reserved word. Enclose in
square brackets as you already do in the first OleDbCommand.
Second, to execute a statement like UPDATE, INSERT, DELETE you call
cmd2.ExecuteNonQuery not ExecuteReader. Don't really needed that call
after the first for cmd.
Third, in the first OleDbCommand (cmd) you use a parameter for
UserID, why in the second one you revert to string concatenation for
user and password? This opens the door to any kind of Sql Injection
Attack.
Fourth, the Using statement assure that every Disposable object
used in your code will be CLOSED thus freeing the memory used by
this commands ALSO IN CASE OF EXCEPTIONS. An example of Using
statement here
(1)
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
and then
(2)
cmd2.ExecuteNonQuery()
Remove (1) - ExecuteNonQuery should do the update.
USER is a keyword in Access, add brackets the same way you have added in the Select statement. Next time, you are faced with a similar problem, print out the statement as Access would see it and try executing it on the database directly - that will point out the errors accurately.
Please use place holders for the update statement similar to the select statement.
I am pretty new to VB and I am not sure why this is not working, basically I am trying to run a stored procedure from my web code. The sp runs just fine in SQL, I've tried it several times so I am sure that is not the problem. I don't want to return any results, I just want to see an "ok" statement if it runs and an error message if it doesn't. The code I am using for the lables (warnings and confirmation) is reused from earlier on the same page, the same goes for the validations (valUpload). I am sure the solution is simple...
Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
Try
Dim bl As New BL.ORG
Dim db As Database = DatabaseFactory.CreateDatabase("MyConnection")
Dim dbCommand As DbCommand
db = DatabaseFactory.CreateDatabase("MyConnection")
dbCommand = db.GetStoredProcCommand("Company.dbo.uspMyStoredProcedure")
dbCommand.CommandTimeout = 300
db.AddInParameter(dbCommand, "ClientID", DbType.String, ddlCompany.SelectedValue)
db.AddInParameter(dbCommand, "startPeriod", DbType.String, ddlStartPeriod.SelectedValue)
db.ExecuteDataSet(dbCommand)
lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
lblWarning.Visible = True
lblConfirmation.Visible = False
Catch ex As Exception
valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
valUpload.IsValid = False
End Try
End Sub
I think the issue here is the line
db.ExecuteDataSet(dbCommand)
From what I can see, the command you want to run is
db.ExecuteNonQuery(dbCommand)
Here is an example site. The code is in C# but I think you can get the basic understanding of it. You could also use a translator on it if you really needed to.
http://msdn.microsoft.com/en-us/magazine/cc188702.aspx#S2
I would rewrite it to something similar to this:
Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
Using cnn As New SqlClient.SqlConnection("MyConnection")
cnn.Open()
Using cmd As New SqlClient.SqlCommand("Company.dbo.uspMyStoredProcedure", cnn)
cmd.CommandTimeout = 30
cmd.Parameters.Add(New SqlClient.SqlParameter("ClientID", SqlDbType.NVarChar, 50) With {.Value = ddlCompany.SelectedValue})
cmd.Parameters.Add(New SqlClient.SqlParameter("startPeriod", SqlDbType.NVarChar, 50) With {.Value = ddlStartPeriod.SelectedValue})
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
valUpload.IsValid = False
End Try
lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
lblWarning.Visible = True
lblConfirmation.Visible = False
End Using
End Using
End Sub
A few notes:
Wrap as little code as possible in a try-catch. In this case, only the database should be a cause of concern (granted you validated the inputs).
The using statement very neatly disposes your connection and command objects in case of problems.
You probably want to refactor the code even futher, keeping the database-calling section in a separate function/sub, and setting labels and UI messages somewhere else.
I've spent a couple of hours trying to find the answer to this, and although there are tutorials all over the 'net none of them work for me (or I am too n00b to understand what they're telling me...)
Anyway, I'm creating users in asp.net using Membership. What I want to do is add the generated UserId to a column in a custom table I've created, to link the stuff in the custom table with the user created in aspnet_Users.
Here's the code I've got for the registration submit button:
Private Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("edinsec").ConnectionString
Dim createStatus As MembershipCreateStatus
Membership.CreateUser(fname.Text, password.Text, email.Text, sq.Text, sa.Text, False, createStatus)
''#Something has to happen here!
Dim insertSQL As String
insertSQL = "INSERT INTO clients (UserId)"
insertSQL &= "VALUES (#userId)"
Using con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand(insertSQL, con)
cmd.Parameters.AddWithValue("#firstname", firstname.Text)
Try
Try
con.Open()
Catch ex As SqlException
MsgBox("Connection Problem - Please Retry Later", 65584, "Connection Error")
End Try
cmd.ExecuteNonQuery()
MsgBox("Thank you for joining us - we will be in touch shortly.", 65600, "Join Up")
Response.Redirect("Default.aspx")
Catch Err As SqlException
MsgBox("Error inserting record - please retry later.", 65584, "Insertion Error")
End Try
con.Close()
End Using
End Sub
As you can see I'm trying to grab the Membership-generated userid and insert it into the clients table. I've tried numerous approaches to grabbing the UserId but none work.
Membership works to create the user, it's just the part afterwards that I'm stuck on.
Any help would be much appreciated :)
I managed it in the end using this code:
Dim userid As Guid = New Guid(Membership.GetUser(username.Text).ProviderUserKey.ToString())
...where username.Text is the content of the username form input, where the user chooses their username.
The relevant parameter line is this:
cmd.Parameters.Add("#UserId", g)
I get a warning about the method I'm using being deprecated, but it works at least!
Membership.CreateUser returns a MembershipUser object. You can get the UserId from that returned object.
MembershipUser user = Membership.CreateUser(...);
Guid userId = (Guid)user.ProviderUserKey;