I have an ASP.NET web application written in vb.net. I have uploaded the application on a web server in the wwroot folder and once I type in the URL with a QueryString, on page_Load it should request that QueryString and store it in the database once in Table1 and another in Table2. Well it is inserting the QueryString to Table 1 but not to Table2. The insertion code is within a Try Catch block but the problem is that I have no idea how to display a server MsgBox with the exception on the client-side.
I have also tried writing a txtFile containing any ex.message on the WebServer itself, but with no luck, even without an exception firing, the txtFile is not created I guess its a path issue. Whether to write the physical path or virtual path both tested without luck.
I am really desperate to know in anyway possible why its inserting the QueryString to Table1 and not Table2.
I am using a class.vb to insert the Querystring. On the main page, I request the QueryString which is a variable (changing) table name (Table2), pass it to a function defined in class.vb and then apply an Insert statement for a predefined un-changing table (Table1) and also using the retrieved QueryString (Table2) name to insert a date and time to both tables.
On MainPage.aspx:
Dim classOBJ AS new Projet.class1
classOBJ.Fun(Request.QueryString("Table"))
In Class1.vb:
Public Sub Fun(ByVal value As String)
Dim date_T As Date = Date.Today
Try
Using myconn As New SqlConnection(ConnString)
myconn.Open()
Dim cmd1 = New SqlCommand("INSERT INTO Table1 (Date_T,Time_T) values (#paramdate, #paramtime)", myconn)
cmd1.Parameters.AddWithValue("#paramdate", date_T)
cmd1.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim cmd2 = New SqlCommand("Insert into [" & value & "] (Date_T, Time_T) values (#paramdate, #paramtime)", myconn)
cmd2.Parameters.AddWithValue("#paramdate", date_T)
cmd2.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd2.ExecuteNonQuery()
cmd2.Dispose()
myconn.Close()
End Using
I am using this notation [ ] because Table's 2 name is a number.
Related
I currently have this SQL insert code in code behind
Dim con As New SqlConnection
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString
con = New SqlConnection(conString)
con.Open()
Dim cmd As New SqlCommand("INSERT INTO AdditionalDaysRequest(Status, AdditionalDays, Justification,RequestDaySubmitted) VALUES (#Status,#AdditionalDays,#Justification,#RequestDaySubmitted)", con)
cmd.Parameters.AddWithValue("#Status", "Pending Request")
cmd.Parameters.AddWithValue("#AdditionalDays", TB_Days.Text)
cmd.Parameters.AddWithValue("#Justification", TB_Justification.Text)
cmd.Parameters.AddWithValue("#RequestDaySubmitted", Date.Now)
cmd.ExecuteNonQuery()
con.Close()
The Id in this table is automatically generated and incremented
What I would like to have now is the Id of this record inserted to add it to another table
Change your query text to add a second statement:
...;SELECT SCOPE_IDENTITY();
The SELECT SCOPE_IDENTITY() statement Returns the last identity value inserted into an identity column in the same scope as from the MSDN article above.
In addition, you can use the ability of the Sql engine to understand and process two or more command statements passed as a single string if you separe the statements with a semicolon.
In this way you have the great benefit to execute a single trip to the database.
Dim cmd As New SqlCommand("INSERT INTO AdditionalDaysRequest(Status, " & _
"AdditionalDays, Justification,RequestDaySubmitted) VALUES " & _
"(#Status,#AdditionalDays,#Justification,#RequestDaySubmitted);" & _
"SELECT SCOPE_IDENTITY()", con)
cmd.Parameters.AddWithValue("#Status", "Pending Request")
cmd.Parameters.AddWithValue("#AdditionalDays", TB_Days.Text)
cmd.Parameters.AddWithValue("#Justification", TB_Justification.Text)
cmd.Parameters.AddWithValue("#RequestDaySubmitted", Date.Now)
Dim result = cmd.ExecuteScalar()
con.Close()
if result IsNot Nothing Then
Dim lastInsertId = Convert.ToInt32(result)
End If
Notice that the two statements are now executed using ExecuteScalar instead of ExecuteNonQuery because we want to catch the result of the last command.
You will want to run a new SqlCommand. Set the value of lastInsertId with this statement:
SELECT SCOPE_IDENTITY()
This would be an additional knowledge.
we have multiple options like:
##IDENTITY
SCOPE_IDENTITY
IDENT_CURRENT
All three functions return last-generated identity values. However
IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
##IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.
I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...
I am developing an ASP.Net VB Web Application
The application contains a GridView which displays the records of a user table from my created datable. The database is an Sql server database.
The code below inserts data into one table and through the built in function ##Identity to insert the most recently added record id (tt_id) from the trainingTbl table and inserting that record id into the userAssessmentTbl. Adding the identity to the second userAssessmentTbl table works fine.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lblUsr2 As Control = FindControlRecursive(MultiTabs, "txtUsr")
Dim strQuery As String
Dim cmd As SqlCommand
strQuery = "Insert into trainingTbl(s_id, t_date, EditorId, wa_id, st_id) values(#s_id , #t_date, #EditorId, #wa_id, #st_id ) Insert into userAssessmentTbl(tt_id, UserId) values(##Identity, #UserId)"
cmd = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#s_id", DDLCourse.Text)
cmd.Parameters.AddWithValue("#t_date", Convert.ToDateTime(txtDate.Text))
cmd.Parameters.AddWithValue("#EditorId", User.Identity.Name.ToString())
cmd.Parameters.AddWithValue("#st_id", myLblStation.Value().ToString)
cmd.Parameters.AddWithValue("#wa_id", myLblWatch.Value().ToString)
cmd.Parameters.AddWithValue("#UserId", lblUsr2.UniqueID.ToString)
InsertUpdateData(cmd)
End Sub
The issue I’m having seems to be centered on how I insert a uniqueidenifier from a GridView into a userAssessmentTbl database!
And how, I guess using a loop I can insert the UserId records from that Gridview (GridView1) into the userAssessmentTbl table along with the looped id from the ##Identity.
This part of the insert parameter seems to be incorrect:
cmd.Parameters.AddWithValue("#UserId", lblUsr2.UniqueID().ToString)
And the error I’m met with is: 'Conversion failed when converting from a character string to uniqueidentifier.'
I’ve also tried it like this:
cmd.Parameters.AddWithValue("#UserId", SqlDbType.UniqueIdentifier).Value().ToString()
And im met with the error: 'Operand type clash: int is incompatible with uniqueidentifier'
The qusetion has slightly changed to how do I Insert a String into SQL DB Where DataType Is Uniqueidentifier?
Any help will be really appreciated.
Well first of all:
##IDENTITY returns the most recently created identity for your current
connection, not necessarily the identity for the recently added row in
a table. Always use SCOPE_IDENTITY() to return the identity of the
recently added row.
Secondly, to asnwer your question:
The SQL type Uniqueidentifier and the CLR type Guid match up.
So instead of passing "#UserId" in as a parameter you need to create a Guid out of the string value.
Dim userID As Guid = New Guid(lblUsr2.UniqueID.ToString)
I am having some trouble getting the correct syntax for a bit if code. I am using vb to insert data into a db and outputting the data as XML, here is the code
<WebMethod()> _
Public Function addTrack(ByVal tTitle As String, ByVal tAlbum As String, ByVal tGenre As String) As String
Dim conn As New SqlConnection("Data Source=MARTIN-LAPTOP\SQLEXPRESS;Initial Catalog=mp3_playlists;Integrated Security=True")
Dim sql As String = "INSERT INTO Tracks (trackTitle, trackAlbum, trackGenre) VALUES ('" & tTitle & "', '" & tAlbum & "', '" & tGenre & "') FOR XML AUTO, ELEMENTS"
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim track As String = cmd.ExecuteScalar()
conn.Close()
Return track
End Function
The code is for a ASP.NET web service, when I click invoke on the website i get the error Incorrect syntax near the keyword 'FOR'. If I remove FOR XML AUTO, ELEMENTS everything works find, db updates but I dont get the data to output as XML. I think the issue is with
the brackets required for the insert values because this issue does not occur if the SQL statement is a SELECT statement which has no brackets but i just cant figure out the correct syntax, thanks for your help
FOR XML AUTO is only used for SELECT statements. So, the issue is not your insert statement, it is your select statement, whereever that is.
I don't know how to go about this. I have a web form with dropdown list, named Recruiter. I have two SQL tables named Perm_Commision_Lookup & UserList.
One of the tables contain email and the other does not. The Perm_Commision_Lookup table does not contain recruiter's email, so I decided to Inner Join it with UserList table which contain recruiter emails. The LookupValue (Recruiter's display name) column from the Perm_Commision_Lookup table is what's displayed to the end user and the pk_LookupID column is the one that's inserted into the database.
What I want to achieve is this: When a user select let's say "John Doe" from the Recruiter dropdown list, I want to send out an email to John Doe alerting him that a form has been submitted and at the same time insert the selected value (pk_LookupID) into the database.
I see that the dropdown list has two field named: DataTextField="LookupValue" and DataValueField="pk_LookupID but how to get the User_Email is my major problem. Below is my SQL select...So far I can do a SQL INNER JOIN...which shown below and also I can display multiple columns into dropdown list...I'm also trying SQLDataReader but I'm just stop with how to get it done.
SELECT Perm_Commision_Lookup.pk_LookupID, Perm_Commision_Lookup.LookupValue, UserList.User_Email
FROM Perm_Commision_Lookup
INNER JOIN UserList ON Perm_Commision_Lookup.LookupUserName = UserList.GM_Username
Any help will be appreciated...
Thanks for your reply! Correct! It's linked via LookupUserName. That's what I have as for now...but still have the problem
Public Sub BindDropDownListData()
' connection string
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using mySqlConnection As New SqlConnection(connectionString)
Try
' open the Sql connection
mySqlConnection.Open()
' Sql Command query to retrieve pk_LookupID, LookupValue, GM_Username, User_Email
Dim mySqlCommand As New SqlCommand(" SELECT Perm_Commision_Lookup.pk_LookupID, Perm_Commision_Lookup.LookupValue, UserList.GM_Username, UserList.User_Email FROM Perm_Commision_Lookup INNER JOIN UserList ON Perm_Commision_Lookup.LookupUserName = UserList.GM_Username order by LookupValue asc", mySqlConnection)
Dim mySqlDataAdapter As New SqlDataAdapter()
mySqlDataAdapter.SelectCommand = mySqlCommand
Dim myDataSet As New DataSet
' mySqlConnection.Open()
' Sql Data Reader to fetch the records row by row in forward direction.
Dim myDataReader As SqlDataReader = mySqlCommand.ExecuteReader()
'Perm_Commision_Lookup
If myDataReader.HasRows Then
' read each row fetched using DataReader
While myDataReader.Read()
Dim li As New ListItem()
'email = myDataReader("User_Email")
li.Value = myDataReader("pk_LookupID")
li.Text = myDataReader("LookupValue")
DropDownList1.Items.Add(li)
End While
End If
myDataReader.Close()
Catch ex As Exception
Label1.Text = ex.Message
Finally
' close the Sql Connection
mySqlConnection.Close()
End Try
DropDownList1.Items.Insert(0, New ListItem("Please Select Recruiter", ""))
End Using
End Sub
1: Use dropdown selectedIndexChanged event.
2: Inside the handler query the database to get the Email and send email.
3: You can selected lookupname from dropdown in the SelectedIndexChanged handler like myddl.SelectedItem.Text or you can get lookupid like myddl.SelectedValue.
From your query it seems your tables are linked via LookupUserName correct or is it LookupId?
And this might help.