2009-11-04 125 views
0

work on asp.net vs05。我的GridView有幾列,其中一些包含文本和一些包含複選框,如果我刪除的複選框那麼它不會產生任何錯誤,如果我不刪除複選框,並希望在Excel導出或PDF然後我得到的波紋管錯誤:出口問題與GridView的複選框

****RegisterForEventValidation can only be called during Render();**** 

爲什麼我得到這個錯誤。如何解決呢?

我的C#代碼:

public void ToExcel() 
{ 
    string attachment = "attachment; filename=Employee.xls"; 
      Response.ClearContent(); 
      Response.AddHeader("content-disposition", attachment); 
      Response.ContentType = "application/ms-excel"; 
      StringWriter stw = new StringWriter(); 
      HtmlTextWriter htextw = new HtmlTextWriter(stw); 
      gvSearch.RenderControl(htextw); 
      Response.Write(stw.ToString()); 
      Response.End(); 
} 


public override void VerifyRenderingInServerForm(Control control) 
    { 

    } 

昨天我張貼的一個問題名稱「的GridView到創先爭優」的.url:http://stackoverflow.com/questions/1665958/gridview-to-excel/1669977#1669977我申請這個問題的答案,但它不work.Help我在Excel導出。

回答

1

你應該嘗試Matt BeresethGridView export utility。它可以管理與checkBoxes和其他HTML控件導出。它通過用實際值替換控件來實現這一點。

alt text http://mattberseth.com/WindowsLiveWriter/ExportGridViewtoExcel_1150B/image0_thumb2.png

看的功能,這是不言自明的。您可以下載該庫並嘗試自己的。

/// <summary> 
/// Replace any of the contained controls with literals 
/// </summary> 
/// <param name="control"></param> 
private static void PrepareControlForExport(Control control) 
{ 
    for (int i = 0; i < control.Controls.Count; i++) 
    { 
     Control current = control.Controls[i]; 
     if (current is LinkButton) 
     { 
      control.Controls.Remove(current); 
      control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); 
     } 
     else if (current is ImageButton) 
     { 
      control.Controls.Remove(current); 
      control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); 
     } 
     else if (current is HyperLink) 
     { 
      control.Controls.Remove(current); 
      control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); 
     } 
     else if (current is DropDownList) 
     { 
      control.Controls.Remove(current); 
      control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); 
     } 
     else if (current is CheckBox) 
     { 
      control.Controls.Remove(current); 
      control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); 
     } 

     if (current.HasControls()) 
     { 
      GridViewExportUtil.PrepareControlForExport(current); 
     } 
    } 
}