JoJo
JoJo

Reputation: 4923

Know if a record was just inserted via C# 4.0?

Is it possible in C# / ASP.NET to know if the ExecuteNonQuery inserted a record or not?

I am checking to make sure the email address does not exist in the table using a subquery.

Is there a way to know if an Insert was made in ASP.NET?

CommandPrizeEmails.Parameters.Add("@Email", SqlDbType.VarChar, 50);
CommandPrizeEmails.Parameters.Add("@DateToday", SqlDbType.DateTime);

CommandPrizeEmails.Parameters["@Email"].Value = txtEmail.Text;
CommandPrizeEmails.Parameters["@DateToday"].Value = DateTime.Now;

CommandPrizeEmails.ExecuteNonQuery();

//int newID = (int)CommandPrizeEmails.ExecuteScalar();

//CommandPrizeEmails.ExecuteNonQuery();
//if (newID >= 1) {
//    divSuccesfulEntry.Visible = true;
//} else {
//    divRepeatEntry.Visible = true;
//}

Upvotes: 2

Views: 1409

Answers (3)

ARJUN
ARJUN

Reputation: 409

bool flg;

flg=cmd.ExecuteNonQuery(); 
if (flg)
{ MessageBox.Show("successfully inserted");
}
else 
{
MessageBox.Show("not inserted");
}

This gives an error as:

Can not implicitly convert type 'int' to 'bool'

Upvotes: -1

senthilkumar2185
senthilkumar2185

Reputation: 2566

ExecuteNonQuery Return Boolean value catch value

ex:

bool flg;

flg=cmd.ExecuteNonQuery(); 
if (flg)
{ msgbox("successfully inserted");}
else {msgbox("not inserted");}

Upvotes: 1

Neha
Neha

Reputation: 2965

You can get the rows affected in return to verify the process.

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.

When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of

rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

http://blogs.msdn.com/b/spike/archive/2009/01/27/sqlcommand-executenonquery-returns-1-when-doing-insert-update-delete.aspx

Upvotes: 1

Related Questions