总是出现下面的错误,我不知道是为什么?
未将对象引用设置到对象的实例。 
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。源错误: 
SqlParameter workParam = null;
行 200: workParam = cmd.Parameters.Add("@NewID",SqlDbType.Int);
行 201: workParam.Direction = ParameterDirection.Output;
行 202:            workParam.Value=cmd.Parameters["@NewID"].Value.ToString();
行 203: string MsgString = "NewID= " + workParam.Value.ToString() ;
行 204:  this.Label1.Text=MsgString;以下是我写的输出参数的存储过程:
 CREATE Procedure ProduceNewID     
 @NewID int output  
as       
declare @Count int       
set @Count=1          
 while (@Count>0)      
   begin          
     if exists(select [id] from supervise_frontdepartment where [id]=@Count)      
       begin       
   set @Count=@Count+1              
        continue          
       end         
      else      
      begin      
   break      
      end      
    end      
select @NewID=@Count  我的程序代码是像下面这样写的: private void GetNewID()
{
string connStr=Str.connStr;

SqlConnection conn=new SqlConnection(connStr);
SqlCommand cmd=new SqlCommand("ProduceNewID",conn);
cmd.CommandType=CommandType.StoredProcedure; SqlParameter workParam = null;
workParam =cmd.Parameters.Add("@NewID",SqlDbType.Int);
workParam.Direction = ParameterDirection.Output;
                   workParam.Value=cmd.Parameters["@NewID"].Value.ToString();

                          string MsgString = "NewID= " + workParam.Value.ToString() ;

                            this.Label1.Text=MsgString;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();  
}请帮忙看一下,到底是怎么回事,谢谢!
  

解决方案 »

  1.   

    SqlParameter workParam = null;这一名改为SqlParameter workParam = new SqlParameter();
      

  2.   

    改成:
    private void GetNewID()
    {
    string connStr=Str.connStr;

    SqlConnection conn=new SqlConnection(connStr);
    SqlCommand cmd=new SqlCommand("ProduceNewID",conn);
    cmd.CommandType=CommandType.StoredProcedure; SqlParameter workParam = null;
    workParam =cmd.Parameters.Add("@NewID",SqlDbType.Int);
    workParam.Direction = ParameterDirection.Output;
                       conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
                           //    workParam.Value=cmd.Parameters["@NewID"].Value.ToString();

                              string MsgString = "NewID= " + workParam.Value.ToString() ;

                                this.Label1.Text=MsgString;
     
    }
      

  3.   

    //设置
    SqlParameter workParam =new SqlParameter("@NewID",SqlDbType.Int);
    workParam.Direction = ParameterDirection.Output;
    cmd.Parameters.Add(workParam);
    //执行
    ...
    //取值
    xxx=workParam.Value;