i use this code for exporting gridview to Excel in asp.net - c#…..but i found some error in my code
i am using stored procedure for sql command and my code behind is as follows….
C# code load event (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();
}
here 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:
As per your guidence i make changes but still gives error….
And ERROR Something like this…it has null value at page_load event thats why it gives error……
Object reference not set to an instance of an object
That’s beacuse you are defining
cmdin button event as below which is local in scope. If you need it globally then try defining accordingly.EDIT:
If you want to
cmdin page_load as well then you can call the SP again in page_load and use it. LikeBut suggest you store the
cmdvalue in session ans reuse it again in page_load like, where your use ofcmdgetting overIn page_load
Then use
cmdin page_load as well per your need