Hi
I am trying to submit some information into a database using an ASP.NET multiline textbox.
I have the following code:
Dim noteContent As String = Replace(txtNoteContent.InnerText.ToString(), vbCrLf, "<br />")
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)
The addNote's function code is:
Public Shared Sub addNote(ByVal JobID As Integer, ByVal NoteFrom As Integer, ByVal NoteTo As Object, ByVal NoteContent As String)
Dim newNote As New Job_Note
newNote.Date = DateTime.Now()
newNote.JobID = JobID
newNote.NoteByStaffID = NoteFrom
If Not NoteTo = Nothing Then
newNote.NoteToStaffID = CInt(NoteTo)
End If
newNote.NoteContent = NoteContent
Try
db.Job_Notes.InsertOnSubmit(newNote)
db.SubmitChanges()
Catch ex As Exception
End Try
End Sub
When it submit's the compiler does not seem to detect that line breaks have been entered into the textbox. I have debugged and stepped through the code, and sure enough, it just ignores the line breaks. If I try and replace another character instead of a line break, it works fine.
It doesn't seem to be anything to do with my function, the LINQ insert or anything like that, it simply just doesn't detect the line breaks. I have tried VbCr, and also chr(13) but they do not work either.
Can someone help me? I have been trying ad searching for over an hour trying to sort this.
Thanks
When you do your replace, you should check for VbCrLf (Windows Line Break), VbLf (Unix Line Break) and VbCr (Mac Line Break). If memory serves correct, the standard newline in a HTML textarea element is "\n" (aka VbLf), so you might just get away with replacing VbCrLf with VbLf in your code, but personally I always check for them all just to be safe.
Example
Dim htmlBreakElement As String = "<br />"
Dim noteContent As String = txtNoteContent.Text _
.Replace(vbCrLf, htmlBreakElement) _
.Replace(vbLf, htmlBreakElement) _
.Replace(vbCr, htmlBreakElement)
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)
Related
I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.
This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.
I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.
You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""
I have a SQL string in Asp.net web page, with vb code behind.
It was working fine before but for unknown reason I start now getting the following error:
Error: Sys.WebForms.PageRequestManagerServerErrorException: Operator '&' is not defined for string "UPDATE db.usersdata SET `SH" and type 'TextBox'.
UPDATE: SH is a string ('SAVE' or 'HIDE')
UPDATE: I am using MySQL database on the background.
Protected Sub savehide_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim SQLstring As String = ""
Dim SH As String
SH = saveorhide.SelectedItem.Value
' the following line is where the error occurs
SQLstring = "UPDATE `db`.`usersdata` SET `SH`='" & SH & "' WHERE `PIC` = '" & Session("UserId") & "'"
Session("SH") = SH
SQLNonQuery_mysql(SQLstring)
CLEARALL()
displaydata()
End Sub
I have spent hours but I cannot find the reason for this, specially when before it was working fine.
This code runs when a dropdownlist field is changed.
The thing it also started to happen to other dropdownlist and SQL string creation code...So it is failing in various VB places now (as I said before it wasn't)
I am wondering if there is a bug or some weird reason why this error is coming out now (and not before) and what would be the solution.
According to the error message, either SH is a TextBox or Session("UserId") is a TextBox.
Since you already showed the declaration of SH, the only suspect remaining is the Session("UserId").
Can you show how you are setting the Session("UserId") value?
My best guess is that you are doing this:
Session("UserId") = TextBox1
you should change it to:
Session("UserId") = TextBox1.Text
(replace TextBox1 with name of your TextBox)
When calling a Sub to populate a System.Collections.Generic.Dictionary with keys and values from a DictionaryEntry(), upon examining the Dictionary in Debug mode every property has a red circle with an X and contains the text "Unable to evaluate expression." It appears to be working, it will even complain if I try to add two entries with the same Key/Value pair. No keys or values are present either, even though my test string (valuesString) is populated.
I am calling the Sub from the ItemInserted event of a FormView (.Net Framework 4, Visual Studio 2013 Webforms Application)
Protected Sub PopulateDictionary(myValues As DictionaryEntry())
Dim de As DictionaryEntry
Dim valuesString As String = String.Empty
Dim myDictionary As New Dictionary(Of String, String)
For Each de In myValues
'This works - the string is populated with key/value pairs
valuesString &= "Key=" & de.Key.ToString() & ", " & _
"Value=" & de.Value.ToString() & "<br/>"
'This doesn't - just get the red circle with an X
myDictionary.Add(de.Key.ToString(), de.Value.ToString())
Next
End Sub
What is going on here? I have restarted Visual Studio with no luck.
odd that this works with the "<br/>". it looks like it's missing the closing quote. (and maybe ToString() is not needed?)
valuesString &= "Key=" & de.Key.ToString() & ", " & _
"Value=" & de.Value.ToString() & "<br/>"
it looks like this:
myDictionary.Add(de.Key.ToString(), de.Value.ToString())
just needs to be:
myDictionary.Add(valuesString)
or (not sure...):
myDictionary.Add(DictionaryEntry())
Note: This code actually codes from a tutorial book I'm reading at the moment, so you can imagine this is frustrating me greatly! I'm building a basic shopping cart, using VB.NET 4, Visual Studio 2010 and MS SQL Server R2 2008. The code below is supposed to remove items from the cart, by reading a session variable, editing it to remove the appropriate ProductID and return the amending string to the session variable. It is then supposed to rebind the data to the gridview (gvCart) to refresh the data...but it seems here there is an error.
Every time I build the site in Visual Studio, it validates fine. But every time I run the site, and attempt to use the remove button it gives me the error:
Incorrect syntax near ')'.
with the IDE pointing me toward the final parenthesis.
I have been pulling my hair out at this for a good 4 hours now, any advice appreciated!
Protected Sub gvCart_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvCart.SelectedIndexChanged
'This method is hooked to the Remove button & is removing items from the cart
Dim strProductId As String = gvCart.SelectedRow.Cells(1).Text
If Session("Cart") IsNot Nothing Then
'Remove selected ProductID from Session string and retrieve session string
Dim strCart As String = Session("Cart").ToString()
Dim arIDs As String() = strCart.Split(",")
'Iterate through ID's in the 'Cart' array and rebuild the string leaving out the selected ID
strCart = String.Empty
For Each str As String In arIDs
'use Trim to remove leading and trailing spaces
If str.Trim() <> strProductId.Trim() Then
strCart += str + ", "
End If
Next
'Remove trailing space and comma
If strCart.Length > 1 Then
strCart = strCart.Trim()
strCart = strCart.Substring(0, strCart.Length - 1)
End If
'Put back into session var
Session("Cart") = strCart
'Rebind gvCart, which forces the sqldatasource to requery
gvCart.DataBind()
End If
End Sub
[EDIT]
I am also including the code that runs for the event sqlCart_Selecting for completion sake:
Protected Sub sqlCart_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles sqlCart.Selecting
Trace.Warn("sqlCart_Selecting") 'aids debugging
Dim strCart As String = String.Empty
If Session("Cart") IsNot Nothing Then
strCart = Session("Cart").ToString
e.Command.CommandText &= " WHERE product.ProductID IN (" + strCart + ") AND culture.CultureID = 'en'"
Else
e.Cancel = True
End If
End Sub
[EDIT]
Also including the SQL query used by the gridview 'gvCart' and the code for displaying the carts contents on another page
<asp:SqlDataSource ID="sqlCart" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" SelectCommand="SELECT product.ProductID, product.Name, product.ProductNumber, product.Color, subcat.Name AS SubcategoryName, cat.Name AS CategoryName, description.Description FROM Production.Product product JOIN Production.ProductSubcategory subcat ON product.ProductSubcategoryID = subcat.ProductSubcategoryID JOIN Production.ProductCategory cat ON subcat.ProductCategoryID = cat.ProductCategoryID JOIN Production.ProductModel model on product.ProductModelID = model.ProductModelID JOIN Production.ProductModelProductDescriptionCulture culture ON model.ProductModelID = culture.ProductModelID JOIN Production.ProductDescription description ON culture.ProductDescriptionID = description.ProductDescriptionID"></asp:SqlDataSource>
Protected Sub btnAddToCart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddToCart.Click
'The contents of the cart will be saved in a Session object as a string of coma-delimited values of ProductID's
Dim strCart As String = String.Empty
Dim strProductID As String = gvProducts.SelectedDataKey.Value.ToString()
If Session("Cart") Is Nothing Then
strCart = strProductID
Else
strCart = Session("Cart").ToString() + ", " + strProductID
End If
Session("Cart") = strCart
lblCart.Text = strCart
End Sub
I will take a shot here, since you are not showing us everything (the SQL query for instance).
But it feels like the SQL query is using IN clause. And it appears to be failing when the cart goes empty.
Since Session("Cart") contains the comma separated values of the product IDs, an empty list would make the following SQL query fail:
select id, name
from products
where id in ()
with the message:
Incorrect syntax near ')'.
You have to show us the portion of code that's reloading the query from Session("Cart"). The query should be reassembled.
But there's one trick you can use! If your product ids are numeric and always greater than zero, change this line:
strCart = String.Empty
to this:
strCart = '-1, '
Update
I will really teach how to fish on this one. :) the problem is here:
Dim strCart As String = String.Empty
If Session("Cart") IsNot Nothing Then
strCart = Session("Cart").ToString
e.Command.CommandText &= " WHERE product.ProductID IN (" + strCart + ") AND culture.CultureID = 'en'"
Else
e.Cancel = True
End If
When cart is empty, Session("Cart") is not Nothing but it's an empty string (provided that you removed the -1 workaround). If Session("Cart") is an empty string the where clause should be " WHERE culture.CultureID = 'en'" only, no mention to product ids. God speed!
I am running into a bit of a problem with ByVal in VBScript. Here's a quick sample script that I wrote to illustrate the issue:
<%
Option Explicit
dim PublicDict
Set PublicDict = createobject("Scripting.Dictionary")
PublicDict.Add "MyKey", "What's up doc?"
response.write OutputStringFromDictionary( PublicDict ) & "<br />"
response.write PublicDict("MyKey")
Set PublicDict = nothing
Function OutputStringFromDictionary( ByVal DictionaryParameter )
DictionaryParameter("MyKey") = replace(DictionaryParameter("MyKey"), "'", "''")
OutputStringFromDictionary = DictionaryParameter("MyKey")
end Function
%>
This script outputs these lines to the browser:
What''s up doc?
What''s up doc?
I was hoping to get:
What''s up doc?
What's up doc?
How do I make it so that OutputStringFromDictionary doesn't modify the original dictionary?
You'd have to clone the actual data somehow. Passing the dictionary by value prevents the dictionary itself from being modified, but you still have pointers to the same items that the dictionary references. You can't modify the dictionary, but you can modify the items it contains.