string que = "SELECT Name FROM StudentInfo where StudentNo=textBox1.Text ";
Every time I run this it always says that
"The multi-part identifier "textBox1.Text" could not be bound".
How do I fix this?
You need to make the query include the value from the textbox. SQL Server doesn't know anything about your textbox - you've just provided the text textBox1.Text
as if it refers to something that SQL Server knows about. However, you shouldn't include the value from your textbox in the SQL itself...
Instead, you should parameterize your SQL, and set the parameter from your textbox as a value to be sent alongside the SQL when you execute the query:
// Assuming an open connection...
int studentNo = int.Parse(textBox1.Text);
string sql = "SELECT Name FROM StudentInfo where StudentNo=@student_no";
using (var command = new SqlCommand(conn, sql))
{
command.Parameters.Add("@student_no", SqlDbType.Int).Value = studentNo;
// Execute the command as normal
}
This assumes that the type of StudentNo
in your database is Int
, of course - adjust accordingly (along with what you do with textBox1.Text
- I'm currently parsing it as an int
).
You should always parameterize your SQL rather than trying include the value within the SQL itself, for three important reasons:
See more on this question at Stackoverflow