Hugo Woesthuis
Hugo Woesthuis

Reputation: 193

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.

Upvotes: 2

Views: 4977

Answers (5)

Darren Wainwright
Darren Wainwright

Reputation: 30747

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("'", "''") + "'"; 

Upvotes: 1

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

You are missing assigning commandText to SqlCommand Object

cmd.CommandText = cmdText; 
string fullName = (string)cmd.ExecuteScalar();

Upvotes: 3

Mostafiz
Mostafiz

Reputation: 7352

First assign your cmdText to cmd.CommandText

 cmd.CommandText = cmdText; 

Then ExecuteScalar() and then convert it using ToString() method

 var temp = cmd.ExecuteScalar();
 string fullName = temp.ToString();

Upvotes: 2

Thern
Thern

Reputation: 1059

Answers to circumvent your problem have already been given. To answer the question why this is occurring: Casting to string can be done with (string) and ToString(), but (string) applied to an object can only convert a string object to string. ExecuteScalar is an Int32 object, so this won't work.

See also here:

Casting to string versus calling ToString

Upvotes: 1

Shaikh Farooque
Shaikh Farooque

Reputation: 2640

use the following code:

var result= cmd.ExecuteScalar();

if (result!= null) {
    fullName = result.ToString();
}

Upvotes: 0

Related Questions