Is there a way to fill an ITemplate by code?
Let's suppose I have an UpdatePanel:
UpdatePanel upnl = new UpdatePanel();
// What should be done next?
//upnl.ContentTemplate = ...
and the result of it would be equivalent of:
<asp:UpdatePanel runat="server" ID="upnl">
<ContentTemplate>
test
</ContentTemplate>
</asp:UpdatePanel>
This will do if I understood your question correctly:
public class YourTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
container.Controls.Add(new LiteralControl("test"));
}
}
...
upnl.ContentTemplate = new YourTemplate();
All the Template enabled Controls in ASP.net must implement System.Web.UI.ITemplate interface to create Template at run time.
But You need not to create custom Template class in case of update
panel. Check UpdatePanel.ContentTemplateContainer Property -
The ContentTemplateContainer property enables you to programmatically add child controls to the UpdatePanel control without having to define a custom template that inherits from the ITemplate interface. If you are adding content to the UpdatePanel control declaratively or through a designer, you should add content to the ContentTemplate property by using a <ContentTemplate> element.
Check this code snippet- For more details check the ContentTemplateContainer link above.
UpdatePanel up1 = new UpdatePanel();
up1.ID = "UpdatePanel1";
Button button1 = new Button();
button1.ID = "Button1";
button1.Text = "Submit";
button1.Click += new EventHandler(Button_Click);
up1.ContentTemplateContainer.Controls.Add(button1);
Page.Form.Controls.Add(up1);
Related
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.
I have a panel inside an update panel on my page which is pre-loaded with a user control, and I want to remove this control and add a new one instead (after a user does some action)
I registered the control:
<%# Register src="~/UserControls/FilesControl.ascx" tagname="FilesControl" tagprefix="files" %>
<asp:Panel ID="pnlFiles" CssClass="selected_tab" runat="server" ClientIDMode="Static">
<files:FilesControl runat="server" ID="filesControl" ShowSearchParams="false" ShowExportControl="false" />
</asp:Panel>
And for adding the new control I wrote this code:
pnlFiles.Controls.Clear();
FilesControl filesHistory = (FilesControl)LoadControl("~/UserControls/FilesControl.ascx");
filesHistory.ShowExportControl =
filesHistory.ShowSearchParams = false;
InitHistoryControl<FilesControl>(filesHistory, daysBack, true); //Sets a datasource to a grid view in the control
pnlFiles.Controls.Add(filesHistory);
But the control is not added to the panel, I don't get any errors even in debug, it is just not there. I can't even see it in the html on view source.
Perhaps because you have these lines:
filesHistory.ShowExportControl =
filesHistory.ShowSearchParams = false;
Try something like:
filesHistory.ShowExportControl = true;
filesHistory.ShowSearchParams = false;
I'm having some problems to bring my UpdatePanel to work properly.I have all the menu-links in a control, of which the Login/Logout-links are dynamically displayed whether you are about to LoginLogin on 1 specific site in the whole projectLogout
HTML-Part:
<asp:UpdatePanel ID="upd_Login" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="plh_LoginOut" runat="server">
</ContentTemplate>
</asp:UpdatePanel>
C#:
// Login/Logout-Link
#region Login
// Clear control
plh_LoginOut.Controls.Clear();
// Logout
if (Request.IsAuthenticated)
{
// Add link to the placeholder
HyperLink lnk_Logout = new HyperLink() { NavigateUrl = ResourceManager.GetString("logout.aspx"), Text = "{#logout#}" };
plh_LoginOut.Controls.Add(lnk_Logout);
}
// Login
else
{
// Session-Fix for the firm.aspx-Page
if (Request.Url.AbsolutePath.ToLower().Contains("firma.aspx"))
{
// Add linkbutton to the placeholder
LinkButton lbtn_Login = new LinkButton() { Text = "{#login#}", CssClass = "loginlink" };
lbtn_Login.Click += new EventHandler(lbtn_Login_Click);
plh_LoginOut.Controls.Add(lbtn_Login);
}
// Standard Logout-link
else
{
// Add link to the placeholder
HyperLink lnk_Logout = new HyperLink() { Text = "{#login#}", CssClass = "loginlink" };
lnk_Logout.Attributes["onclick"] = "ShowLogin(true)";
plh_LoginOut.Controls.Add(lnk_Logout);
}
}
#endregion
This takes all place in a control (.ascx) which is directly embedded in the mastersite. (Scriptmanager is there as well).
Now somehow, in the case of the Linkbutton-Logout-PostBack, the Page really reloads itself (so the Updatepanel does nothing).
Did I forget something or is this an error of some other kind?
Thank you very much for your help
I have a user control which is an image button.
I want that control to be dynamically added "n" times in my webpage.
"n" comes from the database.
I tried this code:
in "aspx":
<%# Register TagPrefix="uc" TagName="imgbtn" Src="~/components/seatfromdb/usercontrol/UC_imgbutton.ascx" %>
.........................................
//some code goes here
.......................................
<uc:imgbtn ID="uc_imgbtn"
runat="server"
/>
in "cs":
for(int i=0;i<5;i++)
{
UserControl uc = new UserControl();
uc = uc_imgbtn;
//uc.Attributes.Keys = "~/images/buttonorange.png";
//uc.ID = "uc" + i.ToString();
//uc.Height = 30;
plhdr_seat.Controls.Add(uc);
plhdr_seat.Controls.Add(new LiteralControl("<br />"));
}
But the control "uc" added to the page only one time. Why?
Please help me with this code.
Do not create UserControl, call Page.LoadControl method to get a new instance of UC_imgbutton.
for(int i = 0; i < 5; i++)
{
UC_imgbutton uc = (UC_imgbutton)LoadControl("~/components/seatfromdb/usercontrol/UC_imgbutton.ascx");
//uc.Attributes.Keys = "~/images/buttonorange.png";
//uc.ID = "uc" + i.ToString();
//uc.Height = 30;
plhdr_seat.Controls.Add(uc);
plhdr_seat.Controls.Add(new LiteralControl("<br />"));
}
This happens because you are always assigning uc_imgbtn to your new UserControl();. In other words you are always assign the same existing control to the plhdr_seat.Controls collection.
Check the Note at this link for more details:
A Control can only be assigned to one Control.ControlCollection at a
time. If the Control is already a child of another control it is
removed from that control before it is added to another control.
If you want to add a new uc_imgbtn control every time to the plhdr_seat.Controls collection you should change your code to:
UserControl uc = new UserControl(); // change this
uc = uc_imgbtn; // remove this
In the first line you must make sure sure you properly initialize the uc control. As far as I can see from your code, this should work: imgbtn uc = new imgbtn();
I am trying to add a ConfirmButtonExtender to my controls collection within a custom control at runtime but can not figure out why the extender will not wire to the button that is being added to the controls collection in the same CreateChildControls method. I did a simple test and added a button explicitly to an aspx page and then creating the extender dynamically in the PreRender of the the .cs file of that page and it still did not work. It seems that the only way to get this to work is to have the actual tags on the .aspx page.
Am I missing something?
protected virtual void CreateChildControls(System.Resources.ResourceManager rm)
{
valValidationSummary = new ValidationSummary();
valValidationSummary.ID = "valValidationSummary";
valValidationSummary.ShowSummary = true;
valValidationSummary.HeaderText = rm.GetString("ValidationSummary");
valValidationSummary.CssClass = "error";
btnGetRates = new LocalizedButton();
btnGetRates.ID = "btnGetStats";
btnGetRates.TextResource = rm.GetString("SubmitButton");
btnGetRates.Text = rm.GetString("SubmitButton");
btnGetRates.CssClass = "inputfield";
btnGetRates.Click += new System.EventHandler(OnSubmitButton_Click);
btnConfirmation = new ConfirmButtonExtender();
btnConfirmation.ID = "rfBtnSubmit_Confirm";
btnConfirmation.ConfirmText = rm.GetString("BAUConfrimation");
btnConfirmation.TargetControlID = "btnGetStats";
this.Controls.Add(btnConfirmation);
this.Controls.Add(valValidationSummary);
this.Controls.Add(btnGetRates);
}
Dumb mistake, I was not rendering the control.