我用這個code for exporting gridview to Excel in asp.net - c#
.....但我found some error in my code
出口GridView控件的Excel文件 - 錯誤
我使用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事件這就是空值爲什麼它給錯誤......
對象引用不設置到對象的實例
ofcourse,你還沒有聲明SqlCommand cmd;在DataTable之前dt = GetData(cmd); '//(在這裏給出錯誤)cmd在當前上下文中不存在。此外,我建議你聲明私人DataTable的GetData(),而不是私人的DataTable的GetData的(SqlCommand cmd) – ray