私はこのcode for exporting gridview to Excel in asp.net - c#
を使用し.....しかし、私found some error in my code
輸出GridViewのにExcelファイル - エラー
....
C#のコードを私はsql command
ためstored procedure
を使用していますし、私のコードが背後にある以下の通りです。ここロードイベント(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();
}
}
ラーフル:
私は変更を加えたが、それでもエラーを与えるあなたguidenceを1として....このような
そしてERROR
何か...それは、Page_LoadイベントのthatsでNULL値を持っていますそれがエラーを返す理由......
オブジェクト参照がオブジェクトのインスタンスに設定されていない
ofcourse、あなたはSqlCommand cmdを宣言していません。 DataTable dt = GetData(cmd)の前。 '//(ここにエラーを与えます)cmdは現在のコンテキストに存在しません '。また、プライベートDataTable GetData()ではなく、プライベートDataTable GetData(SqlCommand cmd)を宣言することをお勧めします。 – ray