Bunion
Bunion

Reputation: 461

Searching for infromation out of a database using text input c#

I'm trying to search for a customers "forename", "surname", and "customerid" to show into a combo box through the use of sql.

     string strSql = "SELECT customerID&\" \" & forename &\" \" & surname AS FullName, surname FROM customer WHERE [customerID]='" + txtCustomerID.Text +"'";

Though with this code I get a "data mismatch exception" which I'm assuming is because I'm using a string and searching for an int?

Upvotes: 1

Views: 570

Answers (2)

Dour High Arch
Dour High Arch

Reputation: 21722

As everyone says; do not construct queries from text fields, use a parameterized query:

SqlCommand sqlQuery = new SqlCommand("SELECT customerID, forename + ' ' + surname AS FullName FROM customer WHERE customerID = @customerID", sqlConnection);
sqlQuery.Parameters.AddWithValue("@customerID", Int32.Parse(txtCustomerID.Text));

You might also want to do some error-checking on txtCustomerID.Text.

Upvotes: 0

Luis Tellez
Luis Tellez

Reputation: 2993

just change this: You dont need to use the '' because its an int

string strSql = @"SELECT customerID +'\' + forename + '\' + surname AS FullName, surname FROM customer WHERE [customerID]=" + txtCustomerID.Text;

But as other have told you this is not a good practice to use string concatenations to build SQL queries, and more if its with parameters or data that you get from the users.

Upvotes: 1

Related Questions