我正在尝试使用带有网格视图的命令按钮显示上传的文件。我的网格视图显示所有记录,并且已为一个选定记录上传文件:
我在asp.net页面中的c#代码是:
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = gvDetails.Rows[index];
if (e.CommandName == "View1")
{
LinkButton lnkbtn = sender as LinkButton;
int fileid = Convert.ToInt32(selectedRow.Cells[1].Text);
int fileid2 = Convert.ToInt32(selectedRow.Cells[2].Text);
string name, type;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select FileName1, FileType1, Emailsent1 from tbSupplierLineItem Where ShoppingCartNo = @scn AND LineItemNo = @itemno";
cmd.Parameters.AddWithValue("@scn", fileid);
cmd.Parameters.AddWithValue("@itemno", fileid2);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.ContentType = dr["FileType1"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["FileName1"] + "\"");
Response.BinaryWrite((byte[])dr["Emailsent1"]);
Response.End();
}
}
}
}
}
在SQL Server 2008中,附件的表字段数据类型是varbinary(MAX)
但是当我在网格视图中单击视图按钮时,它会显示错误,如:
无法将'System.DBNull'类型的对象强制转换为'System.Byte []'。
请帮我修理
我的错误来自我的代码
中的这一行Response.BinaryWrite((byte[])dr["Emailsent1"]);
答案 0 :(得分:0)
尝试
if (dr.IsDbNull("Emailsent1"))
return;