Re: newbie: my code crashe, NULL value

Tech-Archive recommends: Fix windows errors by optimizing your registry



I am not sure why you are selecting 1 after setting the @return. There is no
need unless you are doing something with it. Since you are ExecuteNonQuery,
this is a wasted cycle.

Next, why are you not testing "ret" in your code. If it is -1, the insert
failed for some reason. By testing that you could determine what your issue
is.

Also, why have you not wrapped the open and ExecuteNonQuery() in a try. Here
is a good pattern:

try
{
cn.Open();
int ret = ExecuteNonQuery(cmd);
}
finally
{
cn.Dispose();
}

Not sure what you are returning.

Next suggestion. Do not return until you test the parameter. If it is is
null, the cast to int will blow up (nice technical term ;->).

Be careful with calling thisgs return in a stored proc, as SQL Server
already returns a value (even if you do not declare it) called
@RETURN_VALUE.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com/

*************************************************
Think Outside the Box!
*************************************************
"Jeff" <it_consultant1@xxxxxxxxxxxxxxxxxx> wrote in message
news:unl2osv6GHA.4580@xxxxxxxxxxxxxxxxxxxxxxx
Hey

asp.net 2.0

My code below crashes at the "return
(int)cmd.Parameters["@return"].Value;" line. In the debugging window I see
that when this exception occur, the "return
(int)cmd.Parameters["@return"].Value;" has a NULL value....

public override int SendMessage(MessageDetails message)
{
using (SqlConnection cn = new SqlConnection(this.ConnectionString))
{
SqlCommand cmd = new SqlCommand("AH_network_SendMessages", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@receiver", SqlDbType.NVarChar).Value =
message.Sender;
cmd.Parameters.Add("@sender", SqlDbType.NVarChar).Value =
message.Sender;
cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value =
message.Title;
cmd.Parameters.Add("@body", SqlDbType.NVarChar).Value =
message.Body;
cmd.Parameters.Add("@return", SqlDbType.Int).Direction =
ParameterDirection.Output;
cn.Open();
int ret = ExecuteNonQuery(cmd);
return (int)cmd.Parameters["@return"].Value;
}
}

This is the stored procdure called in the method:
ALTER PROCEDURE dbo.AH_network_SendMessages
@sender nvarchar(256),
@receiver nvarchar(256),
@title nvarchar(100),
@body nvarchar(2000),
@return int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO AH_Messages (sender, receiver, title, body)
VALUES (@sender, @receiver, @title, @body);

set @return = 1;
select 1;
END

Please, what am I doing wrong here?

Jeff



.



Relevant Pages