未将对象引用设置为对象实例 由 DBNull.Value 引起
SqlCommand objsql = new SqlCommand();
.
.
objsql.Parameters.AddWithValue("@Param1", DBNull.Value);
.
.
.
我收到异常错误:
“对象引用未设置为对象的实例”
如果这样做:
objsql.Parameters.AddWithValue("@PaymentMethodID", null);
我收到以下错误: 参数化查询 '(@SupplierQuoteID int,@PaymentMethodID nvarchar(4000),@DueDate d' 需要参数 '@PaymentMethodID',但未提供该参数。"}
PaymentMethodID 是表中接受 null 的列。
此错误发生在此处:
string valHolder = null;
valHolder = objSqlCommand.ExecuteScalar().ToString();
singleValue = Convert.ToInt32(valHolder);
一旦执行objSqlCommand.ExecuteScalar().ToString();就会抛出错误。 记录被插入到表中,但 ExecuteScalar() 不返回任何内容 价值!它应该返回当前最新的自动递增 pk,但事实并非如此。
注意:执行此行时会抛出我上面提到的所有错误
valHolder = objSqlCommand.ExecuteScalar().ToString();
这是完整的错误:
System.NullReferenceException was caught
Message="Object reference not set to an instance of an object."
Source="........"
StackTrace:
at ......DAL.ExecuteSQL(SqlCommand sqlCmd, String typeOfExecution) in C:\Users\....\Desktop\........\DAL.cs:line 136
InnerException:
我应该做什么?
SqlCommand objsql = new SqlCommand();
.
.
objsql.Parameters.AddWithValue("@Param1", DBNull.Value);
.
.
.
I get an exceptional error:
"Object reference not set to an instance of an object"
If i do:
objsql.Parameters.AddWithValue("@PaymentMethodID", null);
I get the following error:
The parameterized query '(@SupplierQuoteID int,@PaymentMethodID nvarchar(4000),@DueDate d' expects the parameter '@PaymentMethodID', which was not supplied."}
PaymentMethodID is a column in table that takes null.
This error happens in here:
string valHolder = null;
valHolder = objSqlCommand.ExecuteScalar().ToString();
singleValue = Convert.ToInt32(valHolder);
Once objSqlCommand.ExecuteScalar().ToString(); is executed, the error is thrown.
The record gets inserted to the table BUT the ExecuteScalar() doesn't return any
value! It should return the current latest auto-incremented pk, but it doesn't.
NOTE: all errors i have mentioned above are thrown when this line is executed
valHolder = objSqlCommand.ExecuteScalar().ToString();
Here is the error in full:
System.NullReferenceException was caught
Message="Object reference not set to an instance of an object."
Source="........"
StackTrace:
at ......DAL.ExecuteSQL(SqlCommand sqlCmd, String typeOfExecution) in C:\Users\....\Desktop\........\DAL.cs:line 136
InnerException:
What should i do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要直接在 ExecuteScalar() 上调用 ToString()。首先调用 objSqlCommand.ExecuteScalar(),然后测试该变量是否为空。这很可能就是正在发生的事情。
如果您正在调用存储过程,请确保
Select SCOPE_IDENTITY()
是存储过程的最后一行,否则将不会返回最后一个自动编号。Don't call ToString() directly on ExecuteScalar(). Call the objSqlCommand.ExecuteScalar() first, then test to see if that variable is nothing. More than likely that is what is happening.
If you are calling a stored procedure, make sure that
Select SCOPE_IDENTITY()
is the last line of your sproc or the last autonumber will not be returned.