【发布时间】:2012-05-07 15:27:29
【问题描述】:
我用这个code for exporting gridview to Excel in asp.net - c#.....但是我found some error in my code
我将stored procedure 用于sql command,我的代码如下......
C# 代码加载事件 (Calling GetData method)
public partial class Admin_ResultDisplay : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnect"].ConnectionString);
cn.Open();
SqlCommand cmd = (SqlCommand)Session["sqlcmd"];
DataTable dt = GetData(cmd);
GridView1.DataSource = dt;
GridView1.DataBind();
}
这里GetData() Method
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DbConnect"].ConnectionString;
//SqlConnection cn = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
Session["sqlcmd"] = cmd;
cmd.CommandType = CommandType.Text; // <= ERROR POINTED HERE....
cmd.Connection = cn;
try
{
cn.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
sda.Dispose();
cn.Dispose();
}
}
拉胡尔:
根据您的指导,我进行了更改,但仍然报错......
还有ERROR 像这样的东西......它在page_load 事件中具有空值,这就是它给出错误的原因......
对象引用未设置为对象的实例
【问题讨论】:
-
当然,你还没有声明SqlCommand cmd;在 DataTable 之前 dt = GetData(cmd);
//(gives error here) cmd is not exist in current context。另外我建议你声明私有 DataTable GetData() 而不是私有 DataTable GetData(SqlCommand cmd)
标签: c# asp.net compiler-errors export-to-excel error-correction