replace function in C# part ii

  • Thread starter Thread starter Andy Sutorius
  • Start date Start date
A

Andy Sutorius

Hi,

I read the thread (2/16/05) regarding a replace function in C# however it
didn't answer my question. I have a string which is building an insert sql
statement and I would like to replace apostrophes of the form fields. I was
trying to do something like this:

string sqlInsertEmails = "insert into tblContent (content, subject) values
('" + Replace(txtBody.Text,"'","''") + "', '" +
Replace(txtSubject.Text,"'","''") + "')";

How can I replace the apostrophe of the form fields (i.e. txtBody.Text)
instead of running a replace function on the entire insert sql statement
which would replace the apostrophes that are needed in the sql statement?

Thanks,

Andy
 
I'm confused. In the code you just posted, you are not calling the
String.Replace() for the entire SQL statement. You are replacing the values
of 2 textboxes, which is what you seem to be asking how to do. Of course,
your example is an unholy mixture of C# and VB syntax. It should read:

string sqlInsertEmails = "insert into tblContent (content, subject) values
"'" +
txtBody.Text.Replace("'", "''") + "', '" +
txtSubject.Text.Replace("'", "''") + "'";

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.
 
Andy:
I'm going to answer this in two parts.

First to answer your question:

"insert into xxx (content, subject) values ('" + txtBody.Text.Replace("'",
"''") + "', '" ....


Secondly, consider using parameterized values instead of concatenation like
this. Do:

someCommand.CommandText = "insert into xxx (content, subject) values (@body,
@subject)"
someCommand.Parameters.Add("@Body", SqlDbType.VarChar, 2048).Value =
txtBody.Text
someCommand.Parameters.Add("@Subject", SqlDbType.VarChar, 128).Value =
txtSibject.Text

you don't need to worry about replace single quotes this way, it provides
more security and can be far more easily replaced with a stored procedure...

Karl
 
Kevin and Karl,

Thank you!

Andy


Karl Seguin said:
Andy:
I'm going to answer this in two parts.

First to answer your question:

"insert into xxx (content, subject) values ('" + txtBody.Text.Replace("'",
"''") + "', '" ....


Secondly, consider using parameterized values instead of concatenation like
this. Do:

someCommand.CommandText = "insert into xxx (content, subject) values (@body,
@subject)"
someCommand.Parameters.Add("@Body", SqlDbType.VarChar, 2048).Value =
txtBody.Text
someCommand.Parameters.Add("@Subject", SqlDbType.VarChar, 128).Value =
txtSibject.Text

you don't need to worry about replace single quotes this way, it provides
more security and can be far more easily replaced with a stored procedure...

Karl
 
Back
Top