存储过程代码:CREATE PROCEDURE ShowCount
@Count INT OUTPUT
AS
SELECT @Count=COUNT(*) FROM Orders
GO
C#代码:SqlConnection sqlCon = new SqlConnection("Server=.;Initial Catalog=Northwind;Integrated Security=SSPI");            try
            {
                sqlCon.Open();                SqlCommand sqlCom = new SqlCommand();
                sqlCom.CommandType = CommandType.StoredProcedure;
                sqlCom.CommandText = "ShowCount";
                sqlCom.Connection = sqlCon;
                sqlCom.Parameters.Add(new SqlParameter("@Count", SqlDbType.Int));
                sqlCom.Parameters["@Count"].Direction = ParameterDirection.Output;                toolCount.Text = sqlCom.Parameters["@Count"].Value.ToString();
            }
            catch (Exception ex)
            {
                toolError.Text = ex.Message;
            }
            finally
            {
                sqlCon.Close();
            }
出现错误提示:未将对象引用设置到对象的事例.

解决方案 »

  1.   

    SqlConnection sqlCon = new SqlConnection("Server=.;Initial Catalog=Northwind;Integrated Security=SSPI");            try
                {
                    sqlCon.Open();                SqlCommand sqlCom = new SqlCommand();
                    sqlCom.CommandType = CommandType.StoredProcedure;
                    sqlCom.CommandText = "ShowCount";
                    sqlCom.Connection = sqlCon;
                    sqlCom.Parameters.Add(new SqlParameter("@Count", SqlDbType.Int));
                    sqlCom.Parameters["@Count"].Direction = ParameterDirection.Output;
                    sqlCom.ExecuteNonQuery();
                    toolCount.Text = sqlCom.Parameters["@Count"].Value.ToString();
                }
                catch (Exception ex)
                {
                    toolError.Text = ex.Message;
                }
                finally
                {
                    sqlCon.Close();
                }