0

我用這個code for exporting gridview to Excel in asp.net - c# .....但我found some error in my code出口GridView控件的Excel文件 - 錯誤

我使用stored proceduresql 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事件這就是空值爲什麼它給錯誤......

對象引用不設置到對象的實例

+0

ofcourse,你還沒有聲明SqlCommand cmd;在DataTable之前dt = GetData(cmd); '//(在這裏給出錯誤)cmd在當前上下文中不存在。此外,我建議你聲明私人DataTable的GetData(),而不是私人的DataTable的GetData的(SqlCommand cmd) – ray

回答

0

這很可能是因爲你在按鈕事件中定義了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值在會話ANS在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"]; 

然後使用cmd in page_load以及您的需要

+0

rahul - thanx你的指導....我嘗試過與全球,但我需要** GetExamResults **程序的參數?所以我該怎麼做?給我一個樣本解決方案,所以我可以理解... – mack28

+0

麥克,請參閱我的編輯。 – Rahul

+0

Rahul - 根據你的指導,我做了更改,但仍然給出了錯誤...它在page_load事件中有null值,這就是爲什麼它給出錯誤...... **對象引用未設置爲對象的實例**'我已經在我的問題中進行了更改,您可以看到它... – mack28

0

錯誤提供了您需要的信息。 cmd確實不存在。您需要在Page_Load事件中創建一個SqlCommand實例。從您提供的代碼中,您只在按鈕事件中定義了cmd,而Page_Load事件不可用。

+0

CM Kanode - 所以在哪個地方我必須作出改變? – mack28

+1

您需要在Page_Load事件中創建一個SqlCommand實例。此外,您根據拉胡爾的建議所做的更改不完整。您正在使用會話變量,但是您是否真的先創建會話變量? –