Answered by:
count in to a textbox

Question
-
User-1578974752 posted
Hi
How can I place the count(salesID) value into a textbox.
cmd.CommandText = "SELECT count(SalesID) FROM SALESaster where SalesID='" + subid.Text + "'"
drd = cmd.ExecuteReader()
Sale.TEXT=
Thanks
Wednesday, January 8, 2020 9:43 AM
Answers
-
User-821857111 posted
cmd.CommandText = "SELECT count(SalesID) FROM SALESaster where SalesID=" + subid.Text; var result = cmd.ExecuteScalar(); Sale.Text = result.ToString();
This assumes that the SalesID cloumn in the database is an integer type, not a varchar, so no apostrophes are needed in the SQL.
Also, you shouldn't really concatenate user input directly into SQL commands. You leave your application open to SQL injection: https://www.mikesdotnetting.com/article/113/preventing-sql-injection-in-asp-net
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, January 8, 2020 11:23 AM
All replies
-
User-821857111 posted
cmd.CommandText = "SELECT count(SalesID) FROM SALESaster where SalesID=" + subid.Text; var result = cmd.ExecuteScalar(); Sale.Text = result.ToString();
This assumes that the SalesID cloumn in the database is an integer type, not a varchar, so no apostrophes are needed in the SQL.
Also, you shouldn't really concatenate user input directly into SQL commands. You leave your application open to SQL injection: https://www.mikesdotnetting.com/article/113/preventing-sql-injection-in-asp-net
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, January 8, 2020 11:23 AM -
User288213138 posted
Hi shsu,
How can I place the count(salesID) value into a textbox.According to your description, I couldn’t understand your requirement clearly.
Do you mean you want to get the query result into a TextBox?
If this is your requirement, I suggest you could try below codes:
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection conn = new SqlConnection(constr)) { conn.Open(); string query = "SELECT count(SalesID) FROM SALESaster where SalesID='" + subid.Text + "'"; SqlCommand cmd = new SqlCommand(query, conn); Object result = cmd.ExecuteScalar(); Sale.Text = result.ToString(); }
Or you want to set the SalesID by TextBox, if so, you can try below code:
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection conn = new SqlConnection(constr)) { conn.Open(); string query =string.Format("SELECT count({0}) FROM SALESaster where SalesID='" + subid.Text + "'", Sale.Text); SqlCommand cmd = new SqlCommand(query, conn); Object result = cmd.ExecuteScalar(); Response.Write(result); }
If I misunderstand your requirement, please post more details information about your requirement.
Best regards,
Sam
Thursday, January 9, 2020 2:40 AM -
User-1578974752 posted
Thanks for the help and the url
Thursday, January 9, 2020 2:55 AM