Possible Duplicate:
ExecuteScalar returns null or DBNull (development or production server)
I have a stored procedure that checks to see if a pre-existing file id is associated to an item. If the select statement returns values, it should be true and assign “true” to the bool. however when the select statement returns a null because it doesn’t exist, my code behind still makes the .Execute return “true”
This is my stored proc:
ALTER PROCEDURE [dbo].[Events_TaskIDExists]
@EventID int
AS
BEGIN
select TaskID from Events where EventID = @EventID
END
and here is my code behind:
public void hasTaskAssociatedToNote()
{
String[] Notes = hidSelectedEventIDs.Value.Split(',');
bool exists = false;
foreach (var note in Notes)
{
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
var command = new SqlCommand("Events_TaskIDExists", connection);
command.Parameters.Add(new SqlParameter("@EventID", SqlDbType.Int));
command.Parameters["@EventID"].Value = Convert.ToInt32(note.Trim());
command.CommandType = CommandType.StoredProcedure;
try
{
connection.Open();
exists = command.ExecuteScalar() != null;//causes true when it returns null......
var temp = command.ExecuteScalar();//this was just to check something else
if (exists)
{
exhibitWarning.Visible = true;
Warning1.Text = "There is an existing Task associated 0.";
}
}
catch (SqlException sql)
{
lblStatus.Text = "Couldn't connect to the Database - Error";
lblStatus.ForeColor = System.Drawing.Color.Red;
}
catch (Exception ex)
{
lblStatus.Text = "An error occured";
lblStatus.ForeColor = System.Drawing.Color.Red;
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}
Your
existsvariable should be set as:A null result from
SqlCommand.ExecuteScalar()returns aDBNull.Value, notnull. Only an empty result set will return anull.Since you’re selecting TaskID based on EventID, my guess is that you don’t have your database constrained to require a TaskID for every Event, and thus you have null TaskID fields. In other words, you have the Event record containing
@EventID, but not an associated Task record (based onTaskID). This condition will return aDBNull.Valuerather than anull.