Net-informations.com
SiteMap  | About    

ASP.NET single quotes

While we are inserting data into the database table we come across the messages like..

  

System.Data.SqlClient.SqlException: Incorrect syntax near ...
Incorrect syntax near '..'. Unclosed quotation mark after the character string ')'

We are getting the above error message because there is a problem while inserting single quoted character using in sql statements. For ex: We want to insert a string like "net-informations's" , the system shows the above error messages, because we are trying to insert a single quoted character using in sql statement.

We can solve this issue by replace any single quote with two quotes like "net-informations''s" .

  insert into tablename (field1) values('net-informations''s')

For avoiding each time adding another single quote to the string , here we implement a function to replace the string with two single quotes.

vb.net
  Public Function convertQuotes(ByVal str As String) As String
	convertQuotes = str.Replace("'", "''")

End Function

C#
  public string convertQuotes(string str)
  {
	return str.Replace("'", "''");

}

From the following program you can see how to handle single quotes in ASP.Net applications.

Default.aspx

  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
	<title>Untitled Page</title>
</head>
<body>
	<form id="form1" runat="server">
	<div>
	<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
	<br />
	<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
	</div>
	</form>
</body>
</html>


Click the following links to see full source code

C# Source Code
VB.NET Source Code
default.aspx.cs
default.aspx.vb





net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.