February 10, 2010 at 9:28 am
I am new to SQL and C# programming and I am trying to create a query using the following string command:
// build the query
string strCommandText = "SELECT CopierTranslator.CopierModel, CopierTranslator.ProductIdentification FROM CopierTranslator";
// add the filter
string filterValue = CopierTransTextBox1.Text;
strCommandText += " WHERE CopierTranslator.CopierModel = " + filterValue;
// add the ordering
strCommandText += " ORDER BY CopierTranslator.ProductIdentification";
// create the command
SqlCommand myCommand = new SqlCommand(strCommandText, myConnection);
// open the database connection
myConnection.Open();
// show the data
GridView1.DataSource = myCommand.ExecuteReader();
GridView1.DataBind();
Where filterValue is the value entered in a text box. The strCommandText builds out to look like this:
"SELECT CopierTranslator.CopierModel, CopierTranslator.ProductIdentification FROM CopierTranslator WHERE CopierTranslator.CopierModel = MX-C311 ORDER BY CopierTranslator.ProductIdentification"
My problem is when the ExecuteReader is run it views the MX-C311 value entered by the user not as a data entry in my db but a column name. If I put " " around the MX-C311 value then ExecuteReader works correctly. Wondering if anyone can provide a suggestion as to how to handle this issue?
Thanks for any assistance.
February 12, 2010 at 4:10 am
February 12, 2010 at 5:05 am
You may find this article interesting.
February 12, 2010 at 7:21 am
stewartc-708166 (2/12/2010)
Of course, the better choice would be to have the select in a stored proc, and to pass the text box value as a parameter.
Absolutely Stewart, stored procedures are a far better way to do this.
We don't know, however, what the OP's doing with this code, whether it's going into a production system or, as I suspect, he's just playing around. Whatever, I thought it would be good to show him the error of his ways early on. 🙂
February 12, 2010 at 7:23 am
February 12, 2010 at 7:24 am
wschampheleer (2/12/2010)
You may find this article interesting.
Yes, thanks Willem, that's the other article I was looking for and couldn't find it. (Now bookmarked)
February 12, 2010 at 7:37 am
Just wating now for the OP to get back to us and say thanks a lot guys I'm glad you pointed this out to me. ;-).
Viewing 7 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply