I have a custom GridView control in my site, basically just a class extending GridView as
ITCSGridView : GridView
This has caused a bug in the export to excel feature which is adding the control to a table cell and then exporting it. The line the error occurs on is:
NewTableCell(ATable).Controls.Add(AControl);
And the exception thrown is:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Prior to me extending the GridView control, the export function was working. The only way I have found to get it to work is to pass the first child control of the custom GridView (which is of type System.Web.UI.WebControl.ChildTable) but then I lose the styling which is required.
Any help would be greatly appreciated.
Edit: Additional code added below
The custom GridView class
public class ITCSGridView : GridView
{
private const string ControlHeaderBackColor = "#B0E0E6";
private const string ControlHeaderForeColor = "#000000";
private const string ControlSelectedRowStyleForeColor = "#335555";
public ITCSGridView() : base()
{
ControlProperties();
HeaderProperties();
PagerProperties();
RowProperties();
}
private void ControlProperties()
{
EnableTheming = true;
Width = new Unit("100%");
SkinID = "ITCSGridView";
CellPadding = 2;
BorderStyle = BorderStyle.None;
HorizontalAlign = HorizontalAlign.Center;
AllowSorting = true;
}
private void HeaderProperties()
{
HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
HeaderStyle.BackColor = ColorTranslator.FromHtml(ControlHeaderBackColor);
HeaderStyle.ForeColor = ColorTranslator.FromHtml(ControlHeaderForeColor);
HeaderStyle.Font.Bold = false;
}
private void PagerProperties()
{
AllowPaging = true;
PageSize = SASMisc.DDLGridViewPageSize;
PagerSettings.Position = PagerPosition.TopAndBottom;
PagerSettings.Mode = PagerButtons.NumericFirstLast;
PagerSettings.FirstPageText = "First";
PagerSettings.LastPageText = "Last";
}
private void RowProperties()
{
RowStyle.Wrap = false;
SelectedRowStyle.ForeColor = ColorTranslator.FromHtml(ControlSelectedRowStyleForeColor);
SelectedRowStyle.Font.Bold = false;
}
Within the class that handles exporting the control to Excel, a System.Web.UI.WebControls.Table Control is created and the GridView control is added to a TableCell within the Table Control, the call to NewTableCell(ATable) is the method that returns the System.Web.UI.WebControls.TableCell. This is basically just:
// The GridView control is passed directly to this method from the aspx.cs
private void AddControlToTable(System.Web.UI.WebControls.Table ATable, Control AControl){
var Table = new System.Web.UI.WebControls.Table();
// Excpetion thrown on line below (this works when using standard GridView instead of custom extended)
NewTableCell(ATable).Controls.Add(AControl);
}
private TableCell NewTableCell(System.Web.UI.WebControls.Table ATable)
{
TableCell Lcell = new TableCell();
TableRow LRow = new TableRow();
LRow.Cells.Add(Lcell);
ATable.Rows.Add(LRow);
return Lcell;
} // private TableCell AddToTable(Table ATable)
You probably have on the same page/or control included on the page piece of markup in which you're doing this:
<%= DateTime.Now %>
The DateTime.Now is just for illustration - the <%= %> matters. This screws up control tree & makes dynamical adding of controls (as you're doing impossible). Workaround is simple - enclose all <%= %> statements into runat="server" control - best control for this is placeholder.
So <%= DateTime.Now %> becomes
<asp:PlaceHolder runat="server">
<%= DateTime.Now %>
</asp:PlaceHolder>
Control tree is consistent and you can add controls dynamically from codebehind once more.
Related
<form runat="server" id="f1">
<div runat="server" id="d">
grid view:
<asp:GridView runat="server" ID="g">
</asp:GridView>
</div>
<asp:TextBox runat="server" ID="t" TextMode="MultiLine" Rows="20" Columns="50"></asp:TextBox>
</form>
Code behind:
public partial class ScriptTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
g.DataSource = new string[] { "a", "b", "c" };
g.DataBind();
TextWriter tw = new StringWriter();
HtmlTextWriter h = new HtmlTextWriter(tw);
d.RenderControl(h);
t.Text = tw.ToString();
}
}
Even the GridView is within a from tag with runat="server", still I am getting this error.
Any clues please ?
You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.
You could avoid this execption by overriding VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
See here and here.
An alternative to overriding VerifyRenderingInServerForm is to remove the grid from the controls collection while you do the render, and then add it back when you are finished before the page loads. This is helpful if you want to have some generic helper method to get grid html because you don't have to remember to add the override.
Control parent = grid.Parent;
int GridIndex = 0;
if (parent != null)
{
GridIndex = parent.Controls.IndexOf(grid);
parent.Controls.Remove(grid);
}
grid.RenderControl(hw);
if (parent != null)
{
parent.Controls.AddAt(GridIndex, grid);
}
Another alternative to avoid the override is to do this:
grid.RenderBeginTag(hw);
grid.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grid.Rows)
{
row.RenderControl(hw);
}
grid.FooterRow.RenderControl(hw);
grid.RenderEndTag(hw);
Just after your Page_Load add this:
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
Note that I don't do anything in the function.
EDIT: Tim answered the same thing. :)
You can also find the answer Here
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
Tim Schmelter's answer helped me a lot, but I had to do one more thing to get it to work on my aspx page. I am using this code to email an embedded GridView control (as HTML), for report automation.
In addition to adding the override sub, I had to do the render() in Me.Handles.onunload, or else I got an error on the RenderControl line.
Protected Sub Page_After_load(sender As Object, e As EventArgs) Handles Me.Unload
If runningScheduledReport Then
Dim stringBuilder As StringBuilder = New StringBuilder()
Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter(stringBuilder)
Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)
GridView1.RenderControl(htmlWriter)
Dim htmlcode As String = stringBuilder.ToString()
Func.SendEmail(Context.Request.QueryString("email").ToString, htmlcode, "Auto Report - Agent Efficiency", Nothing)
End If
End Sub
If i have method like this to Draw my side Menu Dynamically :
private void DrawSideMenu()
{
LinkButton x;
TaskDTO TaskList = new TaskDTO();
List<TaskDTO> List = TaskList.DrawMenu(int.Parse(Session["emp"].ToString()));
HtmlGenericControl myDIV = new HtmlGenericControl("div");
myDIV.ID = "menu8";
HtmlGenericControl myOrderedList = new HtmlGenericControl("ul");//css clss for <ul>
myOrderedList.ID = "orderedList";
myOrderedList.Attributes.Add("class", "task");
HtmlGenericControl listItem1;
string count = "";
foreach (TaskDTO i in List)
{
count = AdjustMenuCount1(i.TaskCode);
x = new LinkButton();
x.ID = i.TaskCode.ToString();
x.Text = i.TaskName + " " + count;
x.Click += new EventHandler(TaskC);
x.Style["FONT-FAMILY"] = "tahoma";
listItem1 = new HtmlGenericControl("li");
listItem1.Attributes.Add("class", "normal");
if (count != "0")
{
listItem1.Controls.Add(x);
myOrderedList.Controls.Add(listItem1);
}
}
myDIV.Controls.Add(myOrderedList);
MenuTD.Controls.Add(myDIV);
Session["SideMenu"] = myDIV;//Save to redraw when page postbacks
}
This Method takes long time to draw my menu.so i call it one time in (!IsPostBack) and save it in session so that i could redraw it like that :
MenuTD.Controls.Add( ((System.Web.UI.Control)(Session["SideMenu"])));
It redraws it successfully but when i click on any link it doesn't hit the event because i thought it's not possible to save the x.Click += new EventHandler(TaskC); in the session ,so i want to know how to loop through my session content to resetting the delegate of my link ?
That idea won't work because if you're not wiring up the Event Handler every time the page is loaded, it won't run.
If we come back to the original issue, you said it's slow. Creating controls at runtime cannot be slow and it's most likely the way you create your list of items:
List<TaskDTO> List = TaskList.DrawMenu(int.Parse(Session["emp"].ToString()));
Instead of storing complete menu, try to store in the Session only List and create all controls as usual. If menu is required on one page only, then use ViewState instead of Session.
Also it makes sense to change the entire code as currently you hardcode all style and layout settings in the code. Create all layout (div, ul, li) in aspx, move all styles in css (for example, you use "task" class but still set "tahoma" in the code). This would simplify the code and bring more flexibility.
List<TaskDTO> List = null;
void Page_Load(object sender, EventArgs e)
{
if (ViewState["List"] != null) {
List = (List<TaskDTO>)ViewState["List"];
} else {
// ArrayList isn't in view state, so we need to load it from scratch.
List = TaskList.DrawMenu(int.Parse(Session["emp"].ToString()));
}
// Code to create menu, e.g.
if (!Page.IsPosBack) {
Repeater1.DataSource = List;
Repeater1.DataBind();
}
}
void Page_PreRender(object sender, EventArgs e)
{
// Save PageArrayList before the page is rendered.
ViewState.Add("List", List);
}
...
<ul id="orderedList">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<li><%# Eval("TaskName") %></li>
</ItemTemplate>
</asp:Repeater>
</ul>
Maybe save it in application level so it only gets built once, then just put the menu into an object and loop through it to re-add the clicks.
I'm afraid that in order for it to work you are going to have to rebind the Click handler on every Page_Load.
Based on your code, and assuming your TaskC is available, you can make this method:
private void RebindMenuHandlers() {
if(Session["SideMenu"] == null)
return; // Your menu has not been built yet
var menu = ((System.Web.UI.Control)(Session["SideMenu"]));
var orderedList = menu.Controls[0];
foreach(var listItem in orderedList){
foreach(var control in listItem){
var linkButton = control as LinkButton;
if(linkButton != null){
linkButton.Click += new EventHandler(TaskC);
}
}
}
}
Then call it on your Page_Load event:
void Page_Load(object sender, EventArgs e)
{
RebindMenuHandlers();
// .... etc
}
I just typed this directly here, so please forgive any silly compilation mistakes, this should be enough to give you the general idea. Hope that helps.
I have a class that defines a Hierarchical RadGrid that I will be using application wide. This grid has many column so this is the best implementation for me, as I will be overriding specific characteristics of the grid based om implementation.
The grid will function in a different manner based on the access level of the user. On a 'basic user level' they will have a Add New Item/Edit Item on the parent grid and Edit, Reject(delete), Approve(Update) on the Child Grid
The next level will be a 'Approver' role. They will NOT have Add New Item/Edit Item on the parent grid and will only have Reject(Edit) on the child. The edit action that the user will take in this role when rejecting an item is that they will be required to enter a comment through a user control that will be launched when the click the reject button. The problem that I am having is that the custom user control is not displaying for a DetailTableView.EditFormSettings when using a GridButtonColumn as the firing event. Any thoughts? TIA
private void SubmittedBatchesRadGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
GridDataItem _dataItem = e.Item as GridDataItem;
if (_dataItem == null) return;
if (e.Item.OwnerTableView.Name == "SubmittedBatchesRadGrid_ChildGrid")
{
SetChildGridCommandColumns(sender, e);
return;
}
if (_dataItem.KeyValues == "{}") { return; }
SetMasterGridCommandColumns(sender, e, _dataItem);
}
private static void SetChildGridCommandColumns(object sender, GridItemEventArgs e)
{
const string _jqueryCode = "if(!$find('{0}').confirm('{1}', event, '{2}'))return false;";
const string _confirmText = "<p>Rejecting this adjustment will mean that you will have to also reject the batch when you are done processing these items.</p><p>Are you sure you want to reject this adjustment?</p>";
((ImageButton)(((GridEditableItem)e.Item)["PolicyEditRecord"].Controls[0])).ImageUrl = "/controls/styles/images/editpencil.png";
ImageButton _btnReject = (ImageButton)((GridDataItem)e.Item)["DeleteTransaction"].Controls[0];
_btnReject.CommandName = "Update";
_btnReject.ImageUrl = "/controls/styles/images/decline.png";
_btnReject.ToolTip = "Reject this item";
//_btnReject.Attributes["onclick"] = string.Format(_jqueryCode, ((Control)sender).ClientID, _confirmText, "Reject Adjustment");
}
private void SubmittedBatchesRadGrid_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
e.DetailTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
e.DetailTableView.EditFormSettings.UserControlName = "/Controls/RejectedAdjustmentComment.ascx";
e.DetailTableView.EditMode = GridEditMode.PopUp;
e.DetailTableView.CommandItemSettings.ShowAddNewRecordButton = false;
GridDataItem _dataItem = e.DetailTableView.ParentItem;
e.DetailTableView.DataSource = AdjustmentAPI.GetAdjustmentsByBatch(Convert.ToInt32(_dataItem.GetDataKeyValue("BatchID").ToString()), PolicyClaimManualAdjustmentCode);
}
It looks like you just need to use OnClientClick instead, and return the value of the confirm dialog.
_btnReject.OnClientClick = "return confirm(\"Are you sure you?\");"
RadAjax has a little quirk when it comes to confirm dialogs, so you may need to use this instead:
_btnReject.OnClientClick = "if (!confirm(\"Are you sure?\")) return false;"
So I thought I would share my solution in case anyone else needs it.
I was barking up the wrong tree with the edit control. Even though a comment is part of the dataset in the RadGrid I don't want to edit the existing record. I decided to create a usercontrol to handle the process. The RadWindow does not take .ascx pages directly so I started with a .aspx wrapper page and inserted the control there. Then I changed the OnClientClick event to launch the RadWindow loading the new aspx file passing the parameters I needed to the usercontrol. The usercontrol saves the comment to the database and updates the record status and then closes.
I modified this section from above:
private static void SetChildGridCommandColumns(object sender, GridItemEventArgs e)
{
((ImageButton)(((GridEditableItem)e.Item)["PolicyEditRecord"].Controls[0])).ImageUrl = "/controls/styles/images/editpencil.png";
ImageButton _btnReject = (ImageButton)((GridDataItem)e.Item)["DeleteTransaction"].Controls[0];
int _manualAdjustmentId = Convert.ToInt32(((GridDataItem)e.Item)["ManualAdjustmentId"].Text);
int _manualAdjustmentBatchId = Convert.ToInt32(((GridDataItem)e.Item)["ManualAdjustmentBatchId"].Text);
_btnReject.ImageUrl = "/controls/styles/images/decline.png";
_btnReject.ToolTip = "Reject this item";
_btnReject.OnClientClick = String.Format("OpenRadWindow('/controls/RejectedAdjustmentComment.aspx?manualAdjustmentId={0}&manualAdjustmentBatchId={1}', 'CommentDialog');return false;", _manualAdjustmentId, _manualAdjustmentBatchId);
}
private void SubmittedBatchesRadGrid_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
//I deleted this section
e.DetailTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
e.DetailTableView.EditFormSettings.UserControlName = "/Controls/RejectedAdjustmentComment.ascx";
e.DetailTableView.EditMode = GridEditMode.PopUp;
//
e.DetailTableView.CommandItemSettings.ShowAddNewRecordButton = false;
GridDataItem _dataItem = e.DetailTableView.ParentItem;
e.DetailTableView.DataSource = AdjustmentAPI.GetAdjustmentsByBatch(Convert.ToInt32(_dataItem.GetDataKeyValue("BatchID").ToString()), PolicyClaimManualAdjustmentCode);
}
I added this to the page with the datagrid:
<telerik:RadWindowManager ID="SubmittedBatchesWindow" runat="server">
<windows>
<telerik:RadWindow ID="CommentDialog" runat="server" Title="Rejected Agjustment Comment Dialog"
Height="350px" Width="440" Left="250px" ReloadOnShow="false" ShowContentDuringLoad="false"
Modal="true" VisibleStatusbar="false" />
</windows>
</telerik:RadWindowManager>
I created a new aspx file and inserted the new ascx control inside
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<uc:RejectedComment id="RejectionComment1" runat="server" />
</form>
I added my code behind for the update in the ascx file, the javascript for the front end
<script language ="javascript" type ="text/javascript" >
//<![CDATA[
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)
return oWindow;
}
function CancelEdit() {
GetRadWindow().close();
}
//]]>
</script>
and last but not least closing the window after a successful update in the button click event;
Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "CancelEdit();", true);
I hope someone else finds this useful. It took me several hours hunting the telerik site to find this piece by piece.
Everything is ok. i van see StyleSheet.css in page source.But css effect can not run my gridview. How can i do that
public class MyGridView : WebPart
{
GridView gvCustomers;
protected override void CreateChildControls()
{
gvCustomers = new GridView();
HtmlHead head = (HtmlHead)Page.Header;
HtmlLink link = new HtmlLink();
link.Attributes.Add("href", Page.ResolveClientUrl("StyleSheet.css"));
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
head.Controls.Add(link);
gvCustomers.CssClass = "tablestyle";
gvCustomers.HeaderStyle.CssClass = "headerstyle";
gvCustomers.AlternatingRowStyle.CssClass = "altrowstyle";
gvCustomers.RowStyle.CssClass = "rowstyle";
this.Controls.Add(gvCustomers);
}
public object DataSource
{
get {
this.EnsureChildControls();
return gvCustomers.DataSource; }
set {
this.EnsureChildControls();
gvCustomers.DataSource = value; }
}
Have you tried a ScriptManagerProxy control? using this control within your user control can determine if the CSS has already been added to your page, and only add one reference to your css file
I've already got my custom header drawing in my GridView using SetRenderMethodDelegate on the header row within the OnRowCreated method. I'm having problems trying to add LinkButtons to the new header row though.
This is what the RenderMethod looks like:
private void RenderSelectionMode(HtmlTextWriter output, Control container)
{
TableHeaderCell cell = new TableHeaderCell();
cell.Attributes["colspan"] = container.Controls.Count.ToString();
AddSelectionModeContents(cell);
cell.RenderControl(output);
output.WriteEndTag("tr");
HeaderStyle.AddAttributesToRender(output);
output.WriteBeginTag("tr");
for(int i = 0; i < container.Controls.Count; i++)
{
DataControlFieldHeaderCell cell = (DataControlFieldHeaderCell)container.Controls[i];
cell.RenderControl(output);
}
}
private void AddSelectionModeContents(Control parent)
{
// TODO: should add css classes
HtmlGenericControl label = new HtmlGenericControl("label");
label.InnerText = "Select:";
selectNoneLK = new LinkButton();
selectNoneLK.ID = "SelectNoneLK";
selectNoneLK.Text = "None";
//selectNoneLK.Attributes["href"] = Page.ClientScript.GetPostBackClientHyperlink(selectNoneLK, "");
//selectNoneLK.Click += SelectNoneLK_Click;
selectNoneLK.Command += SelectNoneLK_Click;
selectAllLK = new LinkButton();
selectAllLK.ID = "SelectAllLK";
selectAllLK.Text = "All";
//selectAllLK.Attributes["href"] = Page.ClientScript.GetPostBackClientHyperlink(selectAllLK, "");
//selectAllLK.Click += SelectAllLK_Click;
selectAllLK.Command += SelectAllLK_Click;
parent.Controls.Add(label);
parent.Controls.Add(selectNoneLK);
parent.Controls.Add(selectAllLK);
}
As you can see, I have tried different ways to get my LinkButtons working (none have worked though). The LinkButtons are rendered as plain anchor tags, like this: <a id="SelectNoneLK">None</a>
I know there is something wrong with the fact that the ID looks like that, since I am using a Master page for this and the ID should be something much longer.
Any help would be appreciated!
Nick
I'd guess that since cell is not part of the control hierarchy (you never add it to the table), the LinkButton's never find an IContainer parent to rewrite their ID's.
I tend to solve these types of issues using the excellent RenderPipe control that allows me to declare my controls in one place, but render them somewhere else.