我有以下情况。我有两种方法用数据填充GridView。具体如下:
protected void btSearch_Click(object sender, EventArgs e)
{
lqPackWeights.WhereParameters.Clear();
ControlParameter cp = new ControlParameter();
cp.Type = TypeCode.String;
if (radBuyer.Checked)
{
cp.ControlID = "ddlProd";
cp.PropertyName = "SelectedValue";
lbRadMiss.Text = "";
}
else if (radProd.Checked)
{
cp.ControlID = "tbxProdAC";
cp.PropertyName = "Text";
lbRadMiss.Text = "";
}
else
{
cp.ControlID = "lbRadMiss";
cp.PropertyName = "Text";
lbRadMiss.Text = "Please check appropriate radio button before you attempt a search";
}
cp.Name = "IDDesc";
lqPackWeights.WhereParameters.Add(cp);
GridView1.DataSourceID = "lqPackWeights";
GridView1.DataBind();
}
并且
protected void btnShowPaper_Click(object sender, EventArgs e)
{
ORWeightsDataClassesDataContext dbPa = new ORWeightsDataClassesDataContext();
int max = 0;
if (int.TryParse(txtbxHowMany.Text, out max))
{
var queryPa = dbPa.tblOnlineReportingCOMPLETEWeights
.Where(x => x.MaterialLevel == "Primary" && x.MaterialText == "Paper" && x.MemberId == "FM00012")
.OrderByDescending(x => x.ProductPercentage).Take(max);
GridView1.DataSource = queryPa;
GridView1.DataBind();
这两种方法都能很好地用他们的approrpiate数据集填充gridview。
我还有以下代码将gridview内容导出到csv:
protected void btnExportCSV_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
导出到csv在第一种情况下(即if / else if场景)运行良好,但是当涉及第二种情况时,只提取标题。
那么这里发生了什么?!我已经添加了几个中断,看起来正在执行导出到csv代码,但是实际的GridView内容没有放在同一个csv文件中。
有什么想法吗?
答案 0 :(得分:1)
您需要添加一个javascript函数。看看这篇解释它的博客文章:
由于
乔恩
答案 1 :(得分:0)
确保在导出之前重新绑定数据。我在一个项目上遇到了同样的问题,因为我们在GridView上关闭了VIEWSTATE,所以在回发时我们试图在网格填充数据之前导出数据。
答案 2 :(得分:0)
我实际上通过删除GridView1.AllowPaging = false解决了这个问题; GridView1.DataBind();来自出口脚本。
不确定它为什么会起作用......但确实如此!