Handling quotes in a textbox?

  • Thread starter Thread starter REB
  • Start date Start date
R

REB

I have a button that executes this sql query:
sqlcmdInsertPhysicalNote.CommandText = "INSERT INTO DriverPhysicalNotes
(DriverInformationID, PhysicalNoteDate, PhysicalNote) VALUES ('" +
ddlDriverName.SelectedValue + "','" + DateTime.Now.ToShortDateString() +
"','" + txtNotes.Text + "')";

I am having a problem when a user enters an apostrophe ' into the textbox it
cause the save to error out. THis is the error

System.Data.SqlClient.SqlException: Unclosed quotation mark before the
character string 'Test in a quote')'. Line 1: Incorrect syntax near 'Test in
a quote')'. at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
DOT.Driver.btnAddPhysicalNote_Click(Object sender, EventArgs e)

How can I keep this from happening? Quotes in the notes section should be
allowed.

Thanks,

REB
 
Use SqlParameter

Tu-Thac

----- REB wrote: ----

I have a button that executes this sql query
sqlcmdInsertPhysicalNote.CommandText = "INSERT INTO DriverPhysicalNote
(DriverInformationID, PhysicalNoteDate, PhysicalNote) VALUES ('"
ddlDriverName.SelectedValue + "','" + DateTime.Now.ToShortDateString()
"','" + txtNotes.Text + "')"

I am having a problem when a user enters an apostrophe ' into the textbox i
cause the save to error out. THis is the erro

System.Data.SqlClient.SqlException: Unclosed quotation mark before th
character string 'Test in a quote')'. Line 1: Incorrect syntax near 'Test i
a quote')'. at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() a
DOT.Driver.btnAddPhysicalNote_Click(Object sender, EventArgs e

How can I keep this from happening? Quotes in the notes section should b
allowed

Thanks

RE
 
As others have posted, you would better to use an SQLParamter, but if
you "must" do this, you need to "escape" the single quote by doubling
it. use

replace(txtNotes.Text, "'", "''")

The second parameter in that is a single quote surrounded by double
quotes. The second parameter is Two Single Quotes surrounded by double
quotes. Keep in mind that there are other characters that can cause
problems too, but the single quote thing is definintely the most
common.
 
Back
Top