我创建了一个函数来获取查询字符串并GridView
在.aspx
页面中创建一个。这工作正常。我有一个导出到csv
返回空文件的函数。SQLDataSource
当我创建和GridView
使用自动化工具时,我毫无问题地使用了这个功能。我相信导出到csv
函数并没有从gridview
网页上的动态中获取数据。我看不出我在哪里犯了错误。我怀疑我的功能很糟糕,因为我没有正确返回GridView
.
protected void Page_Load(object sender, EventArgs e)
{
btnBack.Click += new EventHandler(btnBack_Click);
btnCSVDownload.Click += new EventHandler(btnCSVDownload_Click);
lblLabel.Text = "some text";
string selQuery = "SELECT * FROM Employees";
SqlSelect(selQuery);
}
public string SqlSelect(string selStatement)
{
lblSelectStatement.Text = selStatement;
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["datasource"].ConnectionString;
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = selStatement;
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = MyConnection;
DataTable MyTable = new DataTable();
SqlDataAdapter MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(MyTable);
GridView1.DataSource = MyTable.DefaultView;
GridView1.DataBind();
MyAdapter.Dispose();
MyCommand.Dispose();
MyConnection.Dispose();
return lblSelectStatement.Text;
}
protected void btnCSVDownload_Click(object sender, EventArgs e)
{
ExportToCsv(GridView1);
}
public void ExportToCsv(GridView grv)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=export.csv");
Response.Charset = "";
Response.ContentType = "application/text";
grv.AllowPaging = false;
grv.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < grv.Columns.Count; k++)
{
sb.Append(grv.Columns[k].HeaderText + ','); //add separator
}
sb.Append("\r\n"); //append new line
for (int i = 0; i < grv.Rows.Count; i++)
{
for (int k = 0; k < grv.Columns.Count; k++)
{
grv.Rows[i].Cells[k].Text = ('"' + grv.Rows[i].Cells[k].Text + '"'); //add separator
sb.Append(grv.Rows[i].Cells[k].Text + ',');
}
sb.Append("\r\n"); //append new line
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}