問題
使用 HtmlTextWriter匯出GridView時移除GridView上的超連結
解決方法
RemoveGridViewLink(gridview1);
ExportGridView(gridview1);
Sample code:
public void RemoveGridViewLink(Control targetGridView)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = string.Empty;
for (int i = 0; i < targetGridView.Controls.Count; i++)
{
if (targetGridView.Controls[i].GetType() == typeof(LinkButton)
|| targetGridView.Controls[i].GetType() == typeof(HyperLink)
|| targetGridView.Controls[i].GetType().BaseType == typeof(LinkButton)
|| targetGridView.Controls[i].GetType().BaseType == typeof(HyperLink))
{
l.Text = (targetGridView.Controls[i] as LinkButton).Text;
targetGridView.Controls.Remove(targetGridView.Controls[i]);
targetGridView.Controls.AddAt(i, l);
}
if (targetGridView.Controls[i].HasControls())
RemoveGridViewLink(targetGridView.Controls[i]);
}
}
public void ExportGridView(GridView gv)
{
gv = RemoveGridViewLink(Control gv);
string attachment = "attachment; filename=file.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control){}
沒有留言:
張貼留言