我收到此错误 - >对象引用未设置为对象的实例。 [英] I am getting this error->Object reference not set to an instance of an object.
本文介绍了我收到此错误 - >对象引用未设置为对象的实例。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用gridview从数据库下载文件
这是我的代码...
I want to download a file from database using gridview
Here is my code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, FileName from Career";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
con.Close();
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select FileName, Data, contentType from Career where Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["contentType"].ToString();
fileName = sdr["FileName"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
请告诉我如何解决这个错误?
更新:此行发生错误
Please let me know how to solve this error??
Update: The error occurs on this line
int id = int.Parse((sender as LinkButton).CommandArgument);
推荐答案
你好,
您还没有使用过GridView DataSource属性。像这样修改您的代码
Hello ,
You have not used GridView DataSource property .Modify your code like this way
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, FileName from Career";
cmd.Connection = con;
con.Open();
//Remove this line
// cmd.ExecuteNonQuery();
//Add these lines
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource=dt;
GridView1.DataBind();
con.Close();
}
请您检查并更改您的密码如下:
Could you please check and change your code as below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "YourButtonCommandName")
{
int id = Convert.ToInt32(e.CommandArgument.ToString());
//rest code here
}
}
希望它有助于:)
Hope it Helps :)
这篇关于我收到此错误 - >对象引用未设置为对象的实例。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文