使用FileUpload上传图像文件时出现此错误。我在插入按钮点击事件时收到此错误
public int InsertData(ProductPhoto prdctphoto)
{
int ans = 0;
SqlCommand cmd = DataConnection.GetConnection().CreateCommand();
cmd.CommandText = "prcProductPhoto";
cmd.CommandType = CommandType.StoredProcedure;
// cmd.Parameters.Add(new SqlParameter("@PhotoID", prdctphoto.PhotoID));
cmd.Parameters.Add(new SqlParameter("@PhotoName", prdctphoto.PhotoName));
cmd.Parameters.Add(new SqlParameter("@ExtName", prdctphoto.ExtName));
cmd.Parameters.Add(new SqlParameter("@PhotoType", prdctphoto.PhotoType));
cmd.Parameters.Add(new SqlParameter("@PhotoSize", prdctphoto.PhotoSize));
cmd.Parameters.Add(new SqlParameter("@ProductID", prdctphoto.ProductID));
ans = int.Parse(cmd.ExecuteScalar().ToString());
cmd.Dispose();
DataConnection.CloseConnection();
return ans;
}
我收到了错误
ans = int.Parse(cmd.ExecuteScalar()。ToString());
我的存储过程的代码是
create proc prcProductPhoto
(
@PhotoName Varchar(100),
@ExtName Varchar(100),
@PhotoType Varchar(100),
@PhotoSize int,
@ProductID Int
)
as
insert into ProductPhoto(PhotoName,ExtName,PhotoType,PhotoSize,ProductID) values (@PhotoName,@ExtName,@PhotoType,@PhotoSize,@ProductID)
按钮点击事件的代码是
protected void Insert_Click(object sender, EventArgs e)
{
try
{
if (photoupload.HasFile)
{
ProductPhoto prdctphoto = new ProductPhoto();
prdctphoto.PhotoName = photoupload.FileName;
prdctphoto.PhotoSize = photoupload.PostedFile.ContentLength;
prdctphoto.PhotoType = photoupload.PostedFile.ContentType;
prdctphoto.ExtName = prdctphoto.PhotoName.Substring(prdctphoto.PhotoName.LastIndexOf(".") + 1);
prdctphoto.ProductID = int.Parse(ddlproductname.SelectedValue);
//Response.Write(data.ExtName);
int ans = new InsertAction().InsertData(prdctphoto);
if (ans != 0)
{
string path = Server.MapPath("~/upload/") + ans.ToString() + "." + prdctphoto.ExtName;
photoupload.SaveAs(path);
Response.Write(" File is Uploaded ");
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
答案 0 :(得分:0)
我今天早些时候遇到了这个问题。此错误意味着您应该在“ans”中初始化的值为null。尝试调试它并确保它实际存储一个值。
答案 1 :(得分:0)
ExecuteScalar
将从查询生成的第一个结果集的第一行返回第一列的值。
您的存储过程不会返回任何结果集,因此ExecuteScalar
将返回null
。当您致电cmd.ExecuteScalar().ToString()
时,您正在null
个实例上调用方法,这就是您获得NullReferenceException
的原因。
要解决此问题,您需要更改存储过程以返回适当的值。从查询中看出该值应该是什么并不明显,但假设您要在ProductPhoto
表上有一个要返回的标识列,您可以尝试类似:
create proc prcProductPhoto
(
@PhotoName varchar(100),
@ExtName varchar(100),
@PhotoType varchar(100),
@PhotoSize int,
@ProductID Int
)
As
insert into ProductPhoto
(
PhotoName,
ExtName,
PhotoType,
PhotoSize,
ProductID
)
values
(
@PhotoName,
@ExtName,
@PhotoType,
@PhotoSize,
@ProductID
)
select Scope_Identity()