Question

I have a database and want to check if a specific record already exists.

string sql = "SELECT COUNT(*) from tbl_student WHERE email = '" + mail + "' AND telephone= '" + telephone + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
int userCount = (int)command.ExecuteScalar();
if (userCount > 0)
{
    lblMessage.Text = "Person already exists";
}

The line that is not working. The error message says it is an invalid cast. I have no clue, please help me.

int userCount = (int)command.ExecuteScalar();
Was it helpful?

Solution

Thank you guys for your help. I tried many of your suggestions and they did not work. I then took huMpty duMpty advice and stored it into a var variable. I then converted the var type to int.

Heres is my now working code:

var result = command.ExecuteScalar();
int i = Convert.ToInt32(result);    
if (i == 0)
{
    lblMessage.Text = "Person does not exist";
}
else
{
    lblMessage.Text = "Person exists";
}

OTHER TIPS

I suspect the issue is that it is returning a long or similar. Try using:

int userCount = Convert.ToInt32(command.ExecuteScalar());

If that doesn't work: ask what it is:

object val = command.ExecuteScalar()
Debug.WriteLine(val.GetType().FullName);

Please try this piece of code,

object s = sql.ExecuteScalar();
if (s != null)
{
    Console.WriteLine("Query returned value.");
}
else
{
    Console.WriteLine("Query returned nothing.");
}

command.ExecuteScalar();will return The first column of the first row in the result set, or a null reference if the result set is empty.

it could not result int value

do it like this

if(command.ExecuteScalar() != null){
lblMessage.Text = "Person already exists";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top