我用这个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);
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;
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = (SqlCommand)Session["sqlcmd"];
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
iphone - 如何解决iPhone应用程序hpple HTML解析 'libxml/tree.h
ruby - 为什么在编译ruby-1.9.3-p125时出现clang错误?
c++ - 在UNIX上 “internal compiler error: storage fai