c# - 将Gridview导出到Excel文件-错误

我用这个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();
    }
}

RAHUL:



根据您的指导,我进行了更改,但仍然出现错误。

ERROR这样的东西...它在page_load事件中具有空值,这就是为什么会出错的原因......

对象引用未设置为对象的实例

最佳答案

这是因为您在按钮事件中定义了cmd,如下所示,它在作用域内是本地的。如果全局需要它,请尝试相应地进行定义。

protected void btn_insert_Click(object sender, EventArgs e)    
 {
 try
     {
         SqlCommand cmd = new SqlCommand("GetExamResults", cn); 

编辑:

如果还要在page_load中使用cmd,则可以在page_load中再次调用SP并使用它。喜欢
protected void Page_Load(object sender, EventArgs e) 
 {   
   cn = new SqlConnection(ConfigurationManager.ConnectionStrings     
   ["DbConnect"].ConnectionString);
   SqlCommand cmd = new SqlCommand("GetExamResults", cn);  

但是建议您将cmd值存储在 session 中,然后再次在page_load中重用它,例如,您对cmd的使用已结束
SqlCommand cmd = new SqlCommand();
// Your code goes here

Session["sqlcmd"] = cmd;

在page_load中
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlCommand cmd = (SqlCommand)Session["sqlcmd"];

然后根据需要在page_load中使用cmd

https://stackoverflow.com/questions/10484747/

相关文章:

apache-flex - 类mx.core::DesignLayer could not be f

xml - 构建SLN : CS0008 - CS0115的奇怪错误

actionscript-3 - 1120 : Access of undefined proper

compiler-errors - 添加平移和缩放错误

iphone - 如何解决iPhone应用程序hpple HTML解析 'libxml/tree.h

c++ - 返回类(class)成员时遇到麻烦

ruby - 为什么在编译ruby-1.9.3-p125时出现clang错误?

c++ - 在UNIX上 “internal compiler error: storage fai

testing - Flex Builder : Asset file or directory n

visual-studio-2010 - VS2010 Express 中的 Boost - 重新定