-2

I am trying to initialize the value of a SqlParameter with a string. but why does it not get the value ?

This is what I tried:

 int loadChart(string status)
 {
        connect();

        SqlParameter[] parameters ={
                                      new SqlParameter("status", SqlDbType.VarChar, 10),
                                      new SqlParameter("count", SqlDbType.Int, 4)
                                  };

        parameters[0].Value = status;
        parameters[1].Direction = ParameterDirection.Output;

        SqlCommand cmd = new SqlCommand("sp_Arsenic_getSourceStatusCount", objConnection);

        foreach (SqlParameter param in parameters)
        {
            cmd.Parameters.Add(param);
        }

        cmd.ExecuteNonQuery();

        disConnect();

        int count;
        count =(int) parameters[1].Value;

        return count;
    }
}

The stored procedure:

alter procedure sp_Arsenic_getSourceStatusCount
@status varchar(10),
@count int
as
select @count=COUNT(status) from Arsenic_WaterSource where status=@status
return 1

Inserting a breakpoint I have discovered that the string variable status gets its value "safe" but at parameters[0].Value = (string) status; line parameters[0].value gets null. How to resolve this issue ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66

2 Answers2

3

You did not define your @count parameter as an OUTPUT parameter in your procedure:

alter procedure sp_Arsenic_getSourceStatusCount
@status varchar(10),
@count int OUTPUT  /* <--------------  */
as
select @count=COUNT(status) from Arsenic_WaterSource where status=@status
return 1
D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

Try this:

connect();

SqlCommand cmd = new SqlCommand("sp_Arsenic_getSourceStatusCount", objConnection);

cmd.Parameters.Add(new SqlParameter("@status", status));
SqlParameter pCount = new SqlParameter("@count", 0);
pCount.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(pCount);

cmd.ExecuteNonQuery();

disConnect();

int count = Convert.ToInt32(parameters[1].Value);

return count;

And this:

alter procedure sp_Arsenic_getSourceStatusCount
@status varchar(10),
@count int = 0 OUTPUT
as
set nocount on
select @count=COUNT(status) from Arsenic_WaterSource where status=@status
go
Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30