Gridvew.RenderControl returns empty string - asp.net

I am trying to export a Gridview to excel. I bind the gridview to a collection and can see that it has 6 data rows but when i call the RenderControl it returns an empty string. Below is the code i am using
Gridview1.DataSource = data;
Gridview1.DataBind();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
Gridview1.RenderControl(htw);
var outputHtml = sw.ToString();
when i check the outputHtml it is an empty string. What i am doing wrong in this piece of code.
One thing to note is that gridview is lying inside a form with runat='server' tag and i have not overridden the VerifyRenderingInServerForm method.

My best bet is that you have set the visibility of the GridView to false. This will prevent the control from rendering, because well...it's invisible now. The result is an empty string.
If you don't want to show the GridView, just set the Visibility to true before you execute your rendering code and set it back afterwards:
gv_sample.Visible = true;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gv_sample.RenderControl(htw);
var outputHtml = sw.ToString();
gv_sample.Visible = false;
You possibly will run into trouble with the RenderControl method now. If so, make sure you have set EnableEventValidation="false" in the Page directive and override the VerifyRenderingInServerForm method:
public override void VerifyRenderingInServerForm(Control control)
{
return;
}

Related

How to remove a Gridview from an ASPX page?

I have an Aspx page that displays a GridView. The gridview would appear with data that was depending on which catergory was selected from a drop down menu. The user has the option to then download this as a CSV file (export to CSV). I now want the Gridview not to appear (beacuse it is so large it often just hangs) but instead to be able to download a CSV file with the data from the gridview. I have successfully built the button allowing for the download of this data by clicking the button. However, I now cannot open the page without the gridView appearing. I tried to comment out the Gridview code - this just broke the page. I tried to set the gridview as Visible="False" but this did not work either. What else can I do to prevent the gridview from appearing and the user to be taken straight to a download dialogue box?
wrap your Gridview to a div and set it to display:none in asp.net code –
Ex: <div id="divhidegrid" runat="server" style="display:none;" > <asp:GridView ID="gvtest" runat="server" > </div> like this
You can load your data in DataSet or DataTable from Code Behind and then export it directly to Excel/CSV without assigning it to GridView such as in the following example to export it to Excel:
Public Sub ExportToExcel(dt As DataTable)
If dt.Rows.Count > 0 Then
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.[End]()
End If
End Sub
If you get errors like control must be placed in inside of form tag you may also be required put the following code in your backend (Reference: export-data-to-excel-from-datatable-gridview-aspnet-csharp)
Public Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
C# Version of above code:
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0) {
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
public void VerifyRenderingInServerForm(Control control)
{
// Verifies that the control is rendered
}

Render ascx control from outside page context

When trying to render the HTML of an ascx UserControl from a WebService, I get the error RegisterForEventValidation can only be called during Render.
This is a duplicate of this question. However the answers given do not work...
The solution always involves EnableEventValidation="false" and override VerifyRenderingInServerForm but these are only available on a Page, not on a Control (what the ascx is).
When changing the ascx to an aspx, the following code fails: page.LoadControl("mycontrol.ascx/aspx") and rendering an aspx is apparently not so easy according to this question.
The Question
How can I render my ascx without the exception?
Bonus question:
Why is EnableEventValidation not available on a Control while there are many examples on the net that claim otherwise? (StackOverflow, CodeProject, ...)
I found the solution:
var page = new System.Web.UI.Page();
// Or RenderControl throws 'RegisterForEventValidation can only be called during Render'
page.EnableEventValidation = false;
// Or generates a second hidden field with ID=_VIEWSTATE
page.EnableViewState = false;
var sb = new StringBuilder();
var ctl = (SomeAscx)page.LoadControl("SomeAscx.ascx");
using (var sw = new StringWriter(sb))
using (var htw = new HtmlTextWriter(sw))
{
ctl.RenderControl(htw);
}
string result = sb.ToString();
Key was setting:
page.EnableEventValidation = false;
page.EnableViewState = false;

LinkButton not rendered completely

I have this function that I call in page int event
Protected Function RenderLB(text As String, Id As String, argument As String) As [String]
Using Lb = New System.Web.UI.WebControls.LinkButton
Lb.Text = text
Lb.ID = Id
Lb.Attributes.Add("runat", "Server")
Lb.CommandName = "RedirectFillsession"
Lb.CommandArgument = argument
Dim StringBuilder = New System.Text.StringBuilder()
Using stringWriter = New System.IO.StringWriter(StringBuilder)
Using htmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWriter)
Lb.RenderControl(htmlTextWriter)
End Using
End Using
Return StringBuilder.ToString()
End Using
End Function
the returned value is anchor but CommandName and CommandArgument are not rendered
what should I do to render the CommandName and CommandArgument
CommandName and CommandArgument are never rendered into the output HTML, they are used in the accompanying JavaScript.
Also, you should add your control to the controls collection instead of rendering it manually. That way you can be sure its part of the entire Page Life Cycle.
Controls.Add(Lb)

export gridview to Excel : making changes to gv before it its rendered to control

Im using the following code in order to export a gridview to excel
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
HtmlForm frm = new HtmlForm();
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
EnableViewState = false;
Controls.Add(frm);
frm.Controls.Add(this.myGridView);
frm.RenderControl(hw);
Source for above exporting code
Everything works like a charm.
Except I now have to make changes to the gridview before it gets exported to Excel.
E.g. One change is that I needed to remove a column.
Yet I cant do this:
//I can't remove columns here, since it has not been rendered yet and has 0 columns
frm.Controls.Add(this.myGridView);
frm.RenderControl(hw);
Is there a way to edit the Gridview before it is exported? e.g .Remove a column

Render ASP.Net PlaceHolder .ToString(), not to page

I've searched around and have not been able to find an good solution. I have a custom extension to a PlaceHolder control that will contain expressions that I would like to take the string output of without having to call control.Render(), since that call automatically writes the contents out to the page.
Does anybody know how to get the would be rendered content into a string and prevent the page from containing it?
The often-regurgitated, slightly dated code for this goes something like:
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}

Resources