Hugo Woesthuis Hugo Woesthuis - 2 months ago 7
ASP.NET (C#) Question

Why do I get the error: Can't convert System.Int32 to System.String while I am not using int?

This is my query:

SELECT fullName FROM userData WHERE userName=?


And my C# Code:

var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hugow\Documents\Visual Studio 2015\Projects\OSGS_v2\dataBase.mdf;Integrated Security=True;Connect Timeout=30";
cmd.Connection = con;
string cmdText = null;
string usrName = Request.Cookies["usrData"]["usrName"];
cmdText = "SELECT fullName FROM userData WHERE userName=" + usrName;
cmd.CommandText = cmdText;
con.Open();
string fullName = (string)cmd.ExecuteScalar();
nameLabel.Text = fullName;


Nothing bad right? Well, I get the error: Can't convert System.Int32 to System.String. Convert it to String right? Well, the main problem is: the data ("fullName") is a
String
from it's origin.

So why is this error occurring?

Thanks in advance.

EDIT

I forgot to include
cmd.CommandText = cmdText;
to include in my code snippet, but it was already there in my real code.

Answer

This,

"SELECT fullName FROM userData WHERE userName=" + usrName;

should be

"SELECT fullName FROM userData WHERE userName='" + usrName + "'"; 

SQL Server thinks your usrName is an int because you did not enclose it in quotes.

Also, be aware of single quotes in the actual usrName. Say, for example, you have O'Keefe - you woul need to escape the single '. You do this by doubling them up.

So something like:

"SELECT fullName FROM userData WHERE userName='" + usrName.replace("'", "''") + "'";