Search Results

Search found 34 results on 2 pages for 'itemplate'.

Page 1/2 | 1 2  | Next Page >

  • ASP.Net ITemplate - how do i get the content inside

    - by Mahes
    i have situation where in i would like to read the content of the ITemplate. for example i have something like <WD:PopUpPanel runat="server" ID="MyPoPUp"> <InitScript> // javascript document.getElementByID('urName').value = 'enter your name'; </InitScript> <Content> Name:<asp:TextBox runat="Server" ID="urName"/> </Content> </WD:PopUpPanel> basically the contents inside the InitScript is some javascript, which i want to use in ScriptManager.RegisterScript. so my question is how do i define InitScript??? i tried public ITemplate InitScript; but this give CompiledTemplateBuilder object, how do i read the content inside InitScript ??? thanks for reading...

    Read the article

  • ASP.Net ITemplate - ways of declaring

    - by Mahes
    when we want to define a Template in our user controls we declare a field like this in our user controls public ITemplate MyTemplate { get; set; } so that the user defined templates contents will be represented in MyTemplate, and you can use it. and there are ways to customize the templates, for example [TemplateInstanceAttribute(TemplateInstance.Single)] public ITemplate MyTemplate { get; set; } the above example will enable defines single instance Templates(http://www.nikhilk.net/SingleInstanceTemplates.aspx). i accidentally came across single instance templates and blown away by the power of it. my question is what are all the things possible with ITemplates?? how do we define(use) them (more specifically thru annotations). is there any good documentation available for ITemplates?? (please dont point to msdn)

    Read the article

  • BindData to ITemplate for GridView in code behind

    - by tbischel
    How do I programmatically bind data to a custom item template column for a GridView? So far, I've done something similar to this: TemplateField foo = new TemplateField(); foo.ItemTemplate = new bar(); this.GridView1.Columns.Add(foo); where bar is like this: public class bar : ITemplate { public bar() { } public void InstantiateIn(Control container) { DropDownList ddl = new DropDownList(); container.Controls.Add(ddl); } } (the actual dropdownlist is populated) But ITemplate doesn't contain any kind of data binding properties to implement, and the TemplateField class doesn't seem to have any either... What do I do?

    Read the article

  • Creating an ITemplate from a String

    - by Damon
    I do a lot of work with control templates, and one of the pieces of functionality that I've always wanted is the ability to build a ITemplate from a string.  Throughout the years, the topic has come up from time to time, and I never really found anything about how to do it. though I have run across a number of postings from people who are also wanting the same capability.  As I was messing around with things the other day, I stumbled on how to make it work and I feel really foolish for not figuring it out sooner. ITemplate is an interface that exposes a single method named InstantiateIn.  I've been searching for years for some magical .NET framework component that would take a string and convert it into an ITemplate, when all along I could just build my own.  Here's the code: /// <summary> ///   Allows string-based ITempalte implementations /// </summary> public class StringTemplate : ITemplate {     #region Constructor(s)     ////////////////////////////////////////////////////////////////////////////////////////////     /// <summary>     ///   Constructor     /// </summary>     /// <param name="template">String based version of the control template.</param>     public StringTemplate(string template)     {         Template = template;     }     /// <summary>     ///   Constructor     /// </summary>     /// <param name="template">String based version of the control template.</param>     /// <param name="copyToContainer">True to copy intermediate container contents to the instantiation container, False to leave the intermediate container in place.</param>     public StringTemplate(string template, bool copyToContainer)     {         Template = template;         CopyToContainer = copyToContainer;     }     ////////////////////////////////////////////////////////////////////////////////////////////     #endregion     #region Properties     ////////////////////////////////////////////////////////////////////////////////////////////     /// <summary>     ///   String based template     /// </summary>     public string Template     {         get;         set;     }     /// <summary>     ///   When a StringTemplate is instantiated it is created inside an intermediate control     ///   due to limitations of the .NET Framework.  Specifying True for the CopyToContainer     ///   property copies all the controls from the intermediate container into instantiation     ///   container passed to the InstantiateIn method.     /// </summary>     public bool CopyToContainer     {         get;         set;     }     ////////////////////////////////////////////////////////////////////////////////////////////     #endregion     #region ITemplate Members     ////////////////////////////////////////////////////////////////////////////////////////////     /// <summary>     ///   Creates the template in the specified control.     /// </summary>     /// <param name="container">Control in which to make the template</param>     public void InstantiateIn(Control container)     {         Control tempContainer = container.Page.ParseControl(Template);         if (CopyToContainer)         {             for (int i = tempContainer.Controls.Count - 1; i >= 0; i--)             {                 Control tempControl = tempContainer.Controls[i];                 tempContainer.Controls.RemoveAt(i);                 container.Controls.AddAt(0, tempControl);             }                         }         else         {             container.Controls.Add(tempContainer);         }     }     ////////////////////////////////////////////////////////////////////////////////////////////     #endregion } //class Converting a string into a user control is fairly easy using the ParseControl method from a Page object.  Fortunately, the container passed into the InstantiateIn method has a Page property.  One caveat, however, is that the Page property only has a reference to a Page if the container is located ON the page.  If you run into this problem, you may have to find a creative way to get the Page reference (you can add it to the constructor, store it in the request context, etc).  Another issue that I ran into is that the ParseControl creates a new control, parses the string template, places any controls defined in the template onto the new control it created, and returns that new control with the template on it.  You cannot pass in your own container. Adding this directly to the container provided as a parameter in the InstantiateIn means that you end up with an additional "level" in the control hierarchy.  To avoid this, I added code in that removes each control from the intermediate container and places it into the actual container.  I am not, however, sure about the performance penalty associated with moving a bunch of control from one place to another, nor am I completely sure if doing such a move completely screws something up if you have a code behind, etc.  It seems to work when it's just a template, but my testing was ever-so-slightly shy of thorough when it comes to other crazy scenarios.  As a catch-all, I added a Boolean property called CopyToContainer that allows you to turn the copying on or off depending on your desires and needs. Technorati Tags: .NET,ASP.NET,ITemplate,Development,C#,Custom Controls,Server Controls

    Read the article

  • ASP.NET WebControl ITemplate child controls are null

    - by tster
    Here is what I want: I want a control to put on a page, which other developers can place form elements inside of to display the entities that my control is searching. I have the Searching logic all working. The control builds custom search fields and performs searches based on declarative C# classes implementing my SearchSpec interface. Here is what I've been trying: I've tried using ITemplate on a WebControl which implements INamingContainer I've tried implementing a CompositeControl The closest I can get to working is below. OK I have a custom WebControl [ AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), DefaultProperty("SearchSpecName"), ParseChildren(true), ToolboxData("<{0}:SearchPage runat=\"server\"> </{0}:SearchPage>") ] public class SearchPage : WebControl, INamingContainer { [Browsable(false), PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(typeof(ITemplate), ""), Description("Form template"), TemplateInstance(TemplateInstance.Single), TemplateContainer(typeof(FormContainer))] public ITemplate FormTemplate { get; set; } public class FormContainer : Control, INamingContainer{ } public Control MyTemplateContainer { get; private set; } [Bindable(true), Category("Behavior"), DefaultValue(""), Description("The class name of the SearchSpec to use."), Localizable(false)] public virtual string SearchSpecName { get; set; } [Bindable(true), Category("Behavior"), DefaultValue(true), Description("True if this is query mode."), Localizable(false)] public virtual bool QueryMode { get; set; } private SearchSpec _spec; private SearchSpec Spec { get { if (_spec == null) { Type type = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Name == SearchSpecName).First(); _spec = (SearchSpec)Assembly.GetExecutingAssembly().CreateInstance(type.Namespace + "." + type.Name); } return _spec; } } protected override void CreateChildControls() { if (FormTemplate != null) { MyTemplateContainer = new FormTemplateContainer(this); FormTemplate.InstantiateIn(MyTemplateContainer); Controls.Add(MyTemplateContainer); } else { Controls.Add(new LiteralControl("blah")); } } protected override void RenderContents(HtmlTextWriter writer) { // <snip> } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } } public class FormTemplateContainer : Control, INamingContainer { private SearchPage parent; public FormTemplateContainer(SearchPage parent) { this.parent = parent; } } then the usage: <tster:SearchPage ID="sp1" runat="server" SearchSpecName="TestSearchSpec" QueryMode="False"> <FormTemplate> <br /> Test Name: <asp:TextBox ID="testNameBox" runat="server" Width="432px"></asp:TextBox> <br /> Owner: <asp:TextBox ID="ownerBox" runat="server" Width="427px"></asp:TextBox> <br /> Description: <asp:TextBox ID="descriptionBox" runat="server" Height="123px" Width="432px" TextMode="MultiLine" Wrap="true"></asp:TextBox> </FormTemplate> </tster:SearchPage> The problem is that in the CodeBehind, the page has members descriptionBox, ownerBox and testNameBox. However, they are all null. Furthermore, FindControl("ownerBox") returns null as does this.sp1.FindControl("ownerBox"). I have to do this.sp1.MyTemplateContainer.FindControl("ownerBox") to get the control. How can I make it so that the C# Code Behind will have the controls generated and not null in my Page_Load event so that developers can just do this: testNameBox.Text = "foo"; ownerBox.Text = "bar"; descriptionBox.Text = "baz";

    Read the article

  • Asp.NET custom templated datalist throws argument out of range (index) on button press

    - by MrTortoise
    I have a class BaseTemplate public abstract class BaseTemplate : ITemplate This adds the controls, and provides abstract methods to implement in the inheriting class. The inheriting class then adds its html according to its data source and manages the data binding. This all works fine - I get the control appearing with properly parsed html. The problem is that the base class adds controls into the template that have their own CommandName arguments; the idea is that the class that implements the custom templated dataList will provide the logic of setting the Selected and Edit Indexes. This class also manages the data binding, etc. It sets all of the templates on the datalist in the Init method (which was another cause of this exception). The exception gets thrown when I hit one of these buttons - I have tried hooking up both their click and command events everywhere in case this was the problem. I have also ensured that their command names do not match any of the system ones. The stack trace does not include any references to my methods or objects which is why I am so stuck. It is the most unhelpful message I can imagine. The really frustrating thing is that I cannot get a breakpoint to fire - i.e. the problem is happening after I click the button, but before and of my code can execute. The last time this exception happened was when I had this code in a user control and was assigning the templates to the datalist in the PageLoad. I moved these into init to fix that problem; however, this is a problem that was there then and I have no idea what is causing it let alone how to solve it (and index out of range doesn't really help without knowing what index.) The Exception Details Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index The Stack Trace: [ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index] System.Web.UI.ControlCollection.get_Item(Int32 index) +8665582 System.Web.UI.WebControls.DataList.GetItem(ListItemType itemType, Int32 repeatIndex) +8667655 System.Web.UI.WebControls.DataList.System.Web.UI.WebControls.IRepeatInfoUser.GetItemStyle(ListItemType itemType, Int32 repeatIndex) +11 System.Web.UI.WebControls.RepeatInfo.RenderVerticalRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +8640873 System.Web.UI.WebControls.RepeatInfo.RenderRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +27 System.Web.UI.WebControls.DataList.RenderContents(HtmlTextWriter writer) +208 System.Web.UI.WebControls.BaseDataList.Render(HtmlTextWriter writer) +30 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +163 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32 System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +51 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 The code Base class: public abstract class BaseTemplate : ITemplate { ListItemType _templateType; public BaseTemplate(ListItemType theTemplateType) { _templateType = theTemplateType; } public ListItemType ListItemType { get { return _templateType; } } #region ITemplate Members public void InstantiateIn(Control container) { PlaceHolder ph = new PlaceHolder(); container.Controls.Add(ph); Literal l = new Literal(); switch (_templateType) { case ListItemType.Header: { ph.Controls.Add(new LiteralControl(@"<table><tr>")); InstantiateInHeader(ph); ph.Controls.Add(new LiteralControl(@"</tr>")); break; } case ListItemType.Footer: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInFooter(ph); ph.Controls.Add(new LiteralControl(@"</tr></table>")); break; } case ListItemType.Item: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button select = new Button(); select.ID = "btnSelect"; select.CommandName = "SelectRow"; select.Text = "Select"; ph.Controls.Add(select); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.AlternatingItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInAlternatingItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button select = new Button(); select.ID = "btnSelect"; select.CommandName = "SelectRow"; select.Text = "Select"; ph.Controls.Add(select); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding+=new EventHandler(ph_DataBinding); break; } case ListItemType.SelectedItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button edit = new Button(); edit.ID = "btnEdit"; edit.CommandName = "EditRow"; edit.Text = "Edit"; ph.Controls.Add(edit); Button delete = new Button(); delete.ID = "btnDelete"; delete.CommandName = "DeleteRow"; delete.Text = "Delete"; ph.Controls.Add(delete); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.EditItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInEdit(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button save = new Button(); save.ID = "btnSave"; save.CommandName = "SaveRow"; save.Text = "Save"; ph.Controls.Add(save); Button cancel = new Button(); cancel.ID = "btnCancel"; cancel.CommandName = "CancelRow"; cancel.Text = "Cancel"; ph.Controls.Add(cancel); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.Separator: { InstantiateInSeperator(ph); break; } } } void ph_DataBinding(object sender, EventArgs e) { DataBindingOverride(sender, e); } /// <summary> /// the controls placed into the PlaceHolder will get wrapped in &lt;table&gt;&lt;tr&gt; &lt;/tr&gt;. I.e. you need to provide the column names wrapped in &lt;td&gt;&lt;/td&gt; tags. /// </summary> /// <param name="header"></param> public abstract void InstantiateInHeader(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInItem(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInAlternatingItem(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInEdit(PlaceHolder ph); /// <summary> /// Any html used in the footer will have &lt;/tr&gt;&lt;table&gt; appended to the end. /// &lt;tr&gt; will be appended to the front. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInFooter(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// Adds Delete and Edit Buttons after the table contents. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInSelectedItem(PlaceHolder ph); /// <summary> /// The base class provides no &lt;tr&gt;&lt;/tr&gt; tags /// </summary> /// <param name="ph"></param> public abstract void InstantiateInSeperator(PlaceHolder ph); /// <summary> /// Use this method to bind the controls to their data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public abstract void DataBindingOverride(object sender, EventArgs e); #endregion } Inheriting class: public class NominalGroupTemplate : BaseTemplate { public NominalGroupTemplate(ListItemType theListItemType) : base(theListItemType) { } public override void InstantiateInHeader(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>ID</td><td>Group</td><td>IsPositive</td>")); } public override void InstantiateInItem(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); Label lblGroup = new Label(); lblGroup.ID = "lblGroup"; ph.Controls.Add(lblGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Enabled = false; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInAlternatingItem(PlaceHolder ph) { InstantiateInItem(ph); } public override void InstantiateInEdit(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); TextBox txtGroup = new TextBox(); txtGroup.ID = "txtGroup"; txtGroup.Visible = true; txtGroup.Enabled = true ; ph.Controls.Add(txtGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Visible = true; chkIsPositive.Enabled = true ; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInFooter(PlaceHolder ph) { InstantiateInHeader(ph); } public override void InstantiateInSelectedItem(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); TextBox txtGroup = new TextBox(); txtGroup.ID = "txtGroup"; txtGroup.Visible = true; txtGroup.Enabled = false; ph.Controls.Add(txtGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Visible = true; chkIsPositive.Enabled = false; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInSeperator(PlaceHolder ph) { } public override void DataBindingOverride(object sender, EventArgs e) { PlaceHolder ph = (PlaceHolder)sender; DataListItem li = (DataListItem)ph.NamingContainer; int id = Convert.ToInt32(DataBinder.Eval(li.DataItem, "ID")); string group = (string)DataBinder.Eval(li.DataItem, "Group"); bool isPositive = Convert.ToBoolean(DataBinder.Eval(li.DataItem, "IsPositive")); switch (this.ListItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: { ((Label)ph.FindControl("lblID")).Text = id.ToString(); ((Label)ph.FindControl("lblGroup")).Text = group; ((CheckBox)ph.FindControl("chkIsPositive")).Text = isPositive.ToString(); break; } case ListItemType.EditItem: case ListItemType.SelectedItem: { ((TextBox)ph.FindControl("lblID")).Text = id.ToString(); ((TextBox)ph.FindControl("txtGroup")).Text = group; ((CheckBox)ph.FindControl("chkIsPositive")).Text = isPositive.ToString(); break; } } } } From here I added the control to a page the code behind public partial class NominalGroupbroke : System.Web.UI.UserControl { public void SetNominalGroupList(IList<BONominalGroup> theNominalGroups) { XElement data = Serialiser<BONominalGroup>.SerialiseObjectList(theNominalGroups); ViewState.Add("nominalGroups", data.ToString()); dlNominalGroup.DataSource = theNominalGroups; dlNominalGroup.DataBind(); } protected void Page_init() { dlNominalGroup.HeaderTemplate = new NominalGroupTemplate(ListItemType.Header); dlNominalGroup.ItemTemplate = new NominalGroupTemplate(ListItemType.Item); dlNominalGroup.AlternatingItemTemplate = new NominalGroupTemplate(ListItemType.AlternatingItem); dlNominalGroup.SeparatorTemplate = new NominalGroupTemplate(ListItemType.Separator); dlNominalGroup.SelectedItemTemplate = new NominalGroupTemplate(ListItemType.SelectedItem); dlNominalGroup.EditItemTemplate = new NominalGroupTemplate(ListItemType.EditItem); dlNominalGroup.FooterTemplate = new NominalGroupTemplate(ListItemType.Footer); } protected void Page_Load(object sender, EventArgs e) { dlNominalGroup.ItemCommand += new DataListCommandEventHandler(dlNominalGroup_ItemCommand); } void dlNominalGroup_Init(object sender, EventArgs e) { dlNominalGroup.HeaderTemplate = new NominalGroupTemplate(ListItemType.Header); dlNominalGroup.ItemTemplate = new NominalGroupTemplate(ListItemType.Item); dlNominalGroup.AlternatingItemTemplate = new NominalGroupTemplate(ListItemType.AlternatingItem); dlNominalGroup.SeparatorTemplate = new NominalGroupTemplate(ListItemType.Separator); dlNominalGroup.SelectedItemTemplate = new NominalGroupTemplate(ListItemType.SelectedItem); dlNominalGroup.EditItemTemplate = new NominalGroupTemplate(ListItemType.EditItem); dlNominalGroup.FooterTemplate = new NominalGroupTemplate(ListItemType.Footer); } void dlNominalGroup_DataBinding(object sender, EventArgs e) { } void deleteNominalGroup(int index) { XElement data = XElement.Parse(Convert.ToString( ViewState["nominalGroups"] )); IList<BONominalGroup> list = Serialiser<BONominalGroup>.DeserialiseObjectList(data); FENominalGroup.DeleteNominalGroup(list[index].ID); list.RemoveAt(index); data = Serialiser<BONominalGroup>.SerialiseObjectList(list); ViewState["nominalGroups"] = data.ToString(); dlNominalGroup.DataSource = list; dlNominalGroup.DataBind(); } void updateNominalGroup(DataListItem theItem) { XElement data = XElement.Parse(Convert.ToString( ViewState["nominalGroups"])); IList<BONominalGroup> list = Serialiser<BONominalGroup>.DeserialiseObjectList(data); BONominalGroup old = list[theItem.ItemIndex]; BONominalGroup n = new BONominalGroup(); byte id = Convert.ToByte(((TextBox)theItem.FindControl("lblID")).Text); string group = ((TextBox)theItem.FindControl("txtGroup")).Text; bool isPositive = Convert.ToBoolean(((CheckBox)theItem.FindControl("chkIsPositive")).Text); n.ID = id; n.Group = group; n.IsPositive = isPositive; FENominalGroup.UpdateNominalGroup(old, n); list[theItem.ItemIndex] = n; data = Serialiser<BONominalGroup>.SerialiseObjectList(list); ViewState["nominalGroups"] = data.ToString(); } void dlNominalGroup_ItemCommand(object source, DataListCommandEventArgs e) { DataList l = (DataList)source; switch (e.CommandName) { case "SelectRow": { if (l.EditItemIndex == -1) { l.SelectedIndex = e.Item.ItemIndex; l.EditItemIndex = -1; } break; } case "EditRow": { if (l.SelectedIndex == e.Item.ItemIndex) { l.EditItemIndex = e.Item.ItemIndex; } break; } case "DeleteRow": { deleteNominalGroup(e.Item.ItemIndex); l.EditItemIndex = -1; try { l.SelectedIndex = e.Item.ItemIndex; } catch { l.SelectedIndex = -1; } break; } case "CancelRow": { l.SelectedIndex = l.EditItemIndex; l.EditItemIndex = -1; break; } case "SaveRow": { updateNominalGroup(e.Item); try { l.SelectedIndex = e.Item.ItemIndex; } catch { l.SelectedIndex = -1; } l.EditItemIndex = -1; break; } } } Lots of code there, I'm afraid, but it should build. Thanks if anyone manages to spot my silliness. The BONominalGroup class (please ignore my crazy getHash override, I'm not proud of it). IAudit can just be an empty interface here and all will be fine. It used to inherit from another class, I have cleaned that out - so the serialization logic may be broken here. public class BONominalGroup { public BONominalGroup() #region Fields and properties private Int16 _ID; public Int16 ID { get { return _ID; } set { _ID = value; } } private string _group; public string Group { get { return _group; } set { _group = value; } } private bool _isPositve; public bool IsPositive { get { return _isPositve; } set { _isPositve = value; } } #endregion public override bool Equals(object obj) { bool retVal = false; BONominalGroup ng = obj as BONominalGroup; if (ng!=null) if (ng._group == this._group && ng._ID == this.ID && ng.IsPositive == this.IsPositive) { retVal = true; } return retVal; } public override int GetHashCode() { return ToString().GetHashCode(); } public override string ToString() { return "BONominalGroup{ID:" + this.ID.ToString() + ",Group:" + this.Group.ToString() + ",IsPositive:" + this.IsPositive.ToString() + "," + "}"; } #region IXmlSerializable Members public override void ReadXml(XmlReader reader) { reader.ReadStartElement("BONominalGroup"); this.ID = Convert.ToByte(reader.ReadElementString("id")); this.Group = reader.ReadElementString("group"); this.IsPositive = Convert.ToBoolean(reader.ReadElementString("isPositive")); base.ReadXml(reader); reader.ReadEndElement(); } public override void WriteXml(XmlWriter writer) { writer.WriteElementString("id", this.ID.ToString()); writer.WriteElementString("group", this.Group); writer.WriteElementString("isPositive", this.IsPositive.ToString()); // writer.WriteStartElement("BOBase"); // base.WriteXml(writer); writer.WriteEndElement(); } #endregion }

    Read the article

  • asp.net custom templated datalist - throws argument out of range (index) on button press

    - by MrTortoise
    I have a class BaseTemplate public abstract class BaseTemplate : ITemplate This adds the controls, and provides abstract methods to implement in the inheriting class. The inheriting class then adds its html according to its data source and manages the data binding. this all works fine - I get the control appearing with properly parsed html. the problem is that the base class adds controls into the template that have their own CommandName arguments ... the idea is that the class that implements the custom templated dataList will provide the logic of setting the Selected and Edit Indexes. This class also manages the data binding etc. It sets all of the templates ont he datalist in the Init method (which was another cause of this exception). the exception gets throw when i hit one of these buttons .. but after the ItemCommand event is being processed. The stack trace does not include any references to my methods or objects which is why i am so stuck. The Exception Details Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index The Stack Trace: [ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index] System.Web.UI.ControlCollection.get_Item(Int32 index) +8665582 System.Web.UI.WebControls.DataList.GetItem(ListItemType itemType, Int32 repeatIndex) +8667655 System.Web.UI.WebControls.DataList.System.Web.UI.WebControls.IRepeatInfoUser.GetItemStyle(ListItemType itemType, Int32 repeatIndex) +11 System.Web.UI.WebControls.RepeatInfo.RenderVerticalRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +8640873 System.Web.UI.WebControls.RepeatInfo.RenderRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +27 System.Web.UI.WebControls.DataList.RenderContents(HtmlTextWriter writer) +208 System.Web.UI.WebControls.BaseDataList.Render(HtmlTextWriter writer) +30 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +163 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32 System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +51 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 This is driving me absolutley stark raving bonkers ... im talking cthulu style.

    Read the article

  • ASP.NET GridView - Editing Dynamic Template Columns

    - by user208662
    Hello, I have created a GridView whose columns are dynamically created based on my data source. I have implemented these columns by using the approach described here.Those columns display properly on the initial load. However, I need to implement commanding so that a user can edit / delete a row in the GridView. At this point, I have implemented commanding as I would with a normal GridView. I have a TemplateField with an ItemTemplate that has LinkButton elements for edit and delete. The CommandName for each LinkButton is set to either Edit or Delete respectively. Oddly, when a user clicks either the Edit or Delete link, the data in the GridView disappears. However, I have verified that I am in fact re-binding the data when one of these LinkButton elements is selected. Can anyone provide some suggestions as to what the cause could be? Thank you!

    Read the article

  • Dynamic Column that contains a Repeater

    - by djbyter
    How would I go about doing this programatically? I can do this just fine declaratively, using a template column and then using something like this: ... <TemplateGridColumn> <ItemTemplate> <div> <asp:Image ID="groupImg" CssClass="groupImg" runat="server"/> <asp:Repeater ID="groupItemRpt" runat="server"> <HeaderTemplate> <ul class="groupItemList"> </HeaderTemplate> <ItemTemplate> <li> <asp:Image ID="itemImg" runat="server" /> <asp:HiddenField ID="itemValue" runat="server" /> </li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater> </div> </ItemTemplate> </TemplateGridColumn> ... I am dynamically creating this grid based on the data, so I'm already added columns with one set of controls. But now I need to figure out how to show multiple images, which expand/contract if the groupImg image control is clicked (i just toggle the ul) .. Can anyone point me in the right direction? Thanks.

    Read the article

  • ASP.NET - Nested Custom Templates

    - by Echilon
    I'm thinking about converting a few usercontrols to use templates instead. One of these is my own UC which contains some controls, one of which is a repeater. Is it possible to specifcy a template for the second level usercontrol from the template for the first (which would be on the page)?

    Read the article

  • Loading a Template From a User Control

    - by Ricardo Peres
    What if you wanted to load a template (ITemplate property) from an external user control (.ascx) file? Yes, it is possible; there are a number of ways to do this, the one I'll talk about here is through a type converter. You need to apply a TypeConverterAttribute to your ITemplate property where you specify a custom type converter that does the job. This type converter relies on InstanceDescriptor. Here is the code for it: public class TemplateTypeConverter: TypeConverter { public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return ((sourceType == typeof(String)) || (base.CanConvertFrom(context, sourceType) == true)); } public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return ((destinationType == typeof(InstanceDescriptor)) || (base.CanConvertTo(context, destinationType) == true)); } public override Object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { Object objectFactory = value.GetType().GetField("_objectFactory", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(value); Object builtType = objectFactory.GetType().BaseType.GetField("_builtType", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectFactory); MethodInfo loadTemplate = typeof(TemplateTypeConverter).GetMethod("LoadTemplate"); return (new InstanceDescriptor(loadTemplate, new Object [] { "~/" + (builtType as Type).Name.Replace('_', '/').Replace("/ascx", ".ascx") })); } return base.ConvertTo(context, culture, value, destinationType); } public static ITemplate LoadTemplate(String virtualPath) { using (Page page = new Page()) { return (page.LoadTemplate(virtualPath)); } } } And, on your control: public class MyControl: Control { [Browsable(false)] [TypeConverter(typeof(TemplateTypeConverter))] public ITemplate Template { get; set; } } This allows the following declaration: Hope this helps! SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.brushes.Xml.aliases = ['xml']; SyntaxHighlighter.all();

    Read the article

  • How to change the layout of the CreateUserWizard control?

    - by Bazzz
    How to change just the layout (template) of the CreateUserWizard control programmatically? I would to define another layout (not using the horrid table) but continue to use all the event handling and the creation of the user of the CreateUserWizard control. Just for reference, the following code doesn't work, and produces an unexpected result not representing my Template at all. The "InstantiateIn" method of the ITemplate is not called. public partial class b : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { CreateUserWizard createUserWizard = new CreateUserWizard(); createUserWizard.CreateUserStep.ContentTemplate = new Template(); Panel1.Controls.Add(createUserWizard); } } public class Template : ITemplate { void ITemplate.InstantiateIn(Control container) { container.Controls.Add(new TextBox() { ID = "UserName" }); container.Controls.Add(new TextBox() { ID = "Password" }); container.Controls.Add(new TextBox() { ID = "ConfirmPassword" }); container.Controls.Add(new TextBox() { ID = "Email" }); container.Controls.Add(new PlaceHolder() { ID = "ErrorMessage" }); } } }

    Read the article

  • How can I include additional markup within a 'Content' inner property of an ASP.Net WebControl?

    - by GenericTypeTea
    I've searched the site and I cannot find a solution for my problem, so apologies if it's already been answered (I'm sure someone must have asked this before). I have written a jQuery Popup window that I've packaged up as a WebControl and IScriptControl. The last step is to be able to write the markup within the tags of my control. I've used the InnerProperty attribute a few times, but only for including lists of strongly typed classes. Here's my property on the WebControl: [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public something??? Content { get { if (_content == null) { _content = new something???(); } return _content; } } private something??? _content; Here's the HTML Markup of what I'm after: <ctr:WebPopup runat="server" ID="win_Test" Hidden="false" Width="100px" Height="100px" Modal="true" WindowCaption="Test Window" CssClass="window"> <Content> <div style="display:none;"> <asp:Button runat="server" ID="Button1" OnClick="Button1_Click" /> </div> <%--Etc--%> <%--Etc--%> </Content> </ctr:WebPopup> Unfortunately I don't know what type my Content property should be. I basically need to replicate the UpdatePanel's ContentTemplate. EDIT: So the following allows a Template container to be automatically created, but no controls show up, what's wrong with what I'm doing? [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ITemplate Content { get { return _content; } set { _content = value; } } private ITemplate _content; EDIT2: Overriding the CreateChildControls allows the controls within the ITemplate to be rendered: protected override void CreateChildControls() { if (this.Content != null) { this.Controls.Clear(); this.Content.InstantiateIn(this); } base.CreateChildControls(); } Unfortunately I cannot now access the controls within the ITemplate from the codebehind file on the file. I.e. if I put a button within my mark as so: <ctr:WebPopup runat="server" ID="win_StatusFilter"> <Content> <asp:Button runat="server" ID="btn_Test" Text="Cannot access this from code behind?" /> </Content> </ctr:WebPopup> I then cannot access btn_Test from the code behind: protected void Page_Load(object sender, EventArgs e) { btn_Test.Text = "btn_Test is not present in Intellisense and is not accessible to the page. It does, however, render correctly."; }

    Read the article

  • Dynamic gridview columns event problem

    - by ropstah
    Hi, i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row. I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because: _OnDataBound is not called on every postback (same for _OnRowDataBound) _OnInit is not possible because the 'Inner table' for the Gridview is added after Init _OnLoad is not possible because the 'selected' row is not selected yet. I can add the columns to the dynamic GridView based on my ITemplate class. But now the button events won't fire.... Any suggestions? The dynamic adding of the gridview: Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender Dim g As GridView = sender g.DataBind() If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count &gt; 0 Then Dim t As Table = g.Controls(0) Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal) Dim c As New TableCell Dim visibleColumnCount As Integer = 0 For Each d As DataControlField In g.Columns If d.Visible Then visibleColumnCount += 1 End If Next c.ColumnSpan = visibleColumnCount Dim ph As New PlaceHolder ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value)) c.Controls.Add(ph) r.Cells.Add(c) t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r) End If End Sub Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView Dim col As Interfaces.esColumnMetadata Dim coll As New BLL.ViewStmCollection Dim entity As New BLL.ViewStm Dim query As BLL.ViewStmQuery = coll.Query Me._gridStock.AutoGenerateColumns = False Dim buttonf As New TemplateField() buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button") buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button") buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button") Me._gridStock.Columns.Add(buttonf) For Each col In coll.es.Meta.Columns Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name) Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name) Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name) Dim f As New TemplateField() f.HeaderTemplate = headerf f.ItemTemplate = itemf f.EditItemTemplate = editf Me._gridStock.Columns.Add(f) Next query.Where(query.PnmAutoKey.Equal(PnmAutoKey)) coll.LoadAll() Me._gridStock.ID = "gvChild" Me._gridStock.DataSource = coll AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand Me._gridStock.DataBind() Return Me._gridStock End Function The ITemplate class: Public Class QuantityTemplateField : Implements ITemplate Private _itemType As ListItemType Private _fieldName As String Private _infoType As String Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String) Me._itemType = ItemType Me._fieldName = FieldName Me._infoType = InfoType End Sub Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn Select Case Me._itemType Case ListItemType.Header Dim l As New Literal l.Text = "&lt;b&gt;" & Me._fieldName & "</b>" container.Controls.Add(l) Case ListItemType.Item Select Case Me._infoType Case "Button" Dim ib As New Button() Dim eb As New Button() ib.ID = "InsertButton" eb.ID = "EditButton" ib.Text = "Insert" eb.Text = "Edit" ib.CommandName = "Edit" eb.CommandName = "Edit" AddHandler ib.Click, AddressOf Me.InsertButton_OnClick AddHandler eb.Click, AddressOf Me.EditButton_OnClick container.Controls.Add(ib) container.Controls.Add(eb) Case Else Dim l As New Label l.ID = Me._fieldName l.Text = "" AddHandler l.DataBinding, AddressOf Me.OnDataBinding container.Controls.Add(l) End Select Case ListItemType.EditItem Select Case Me._infoType Case "Button" Dim b As New Button b.ID = "UpdateButton" b.Text = "Update" b.CommandName = "Update" b.OnClientClick = "return confirm('Sure?')" container.Controls.Add(b) Case Else Dim t As New TextBox t.ID = Me._fieldName AddHandler t.DataBinding, AddressOf Me.OnDataBinding container.Controls.Add(t) End Select End Select End Sub Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("insert click") End Sub Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("edit click") End Sub Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs) Dim boundValue As Object = Nothing Dim ctrl As Control = sender Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName) Select Case Me._itemType Case ListItemType.Item Dim fieldLiteral As Label = sender fieldLiteral.Text = boundValue.ToString() Case ListItemType.EditItem Dim fieldTextbox As TextBox = sender fieldTextbox.Text = boundValue.ToString() End Select End Sub End Class

    Read the article

  • ASP.NET Controls – CommunityServer Captcha ControlAdapter, a practical case

    - by nmgomes
    The ControlAdapter is available since .NET framework version 2.0 and his main goal is to adapt and customize a control render in order to achieve a specific behavior or layout. This customization is done without changing the base control. A ControlAdapter is commonly used to custom render for specific platforms like Mobile. In this particular case the ControlAdapter was used to add a specific behavior to a Control. In this  post I will use one adapter to add a Captcha to all WeblogPostCommentForm controls within pontonetpt.com CommunityServer instance. The Challenge The ControlAdapter complexity is usually associated with the complexity/structure of is base control. This case is precisely one of those since base control dynamically load his content (controls) thru several ITemplate. Those of you who already played with ITemplate knows that while it is an excellent option for control composition it also brings to the table a big issue: “Controls defined within a template are not available for manipulation until they are instantiated inside another control.” While analyzing the WeblogPostCommentForm control I found that he uses the ITemplate technique to compose it’s layout and unfortunately I also found that the template content vary from theme to theme. This could have been a problem but luckily WeblogPostCommentForm control template content always contains a submit button with a well known ID (at least I can assume that there are a well known set of IDs). Using this submit button as anchor it’s possible to add the Captcha controls in the correct place. Another important finding was that WeblogPostCommentForm control inherits from the WrappedFormBase control which is the base control for all CommunityServer input forms. Knowing this inheritance link the main goal has changed to became the creation of a base ControlAdapter that  could be extended and customized to allow adding Captcha to: post comments form contact form user creation form. And, with this mind set, I decided to used the following ControlAdapter base class signature :public abstract class WrappedFormBaseCaptchaAdapter<T> : ControlAdapter where T : WrappedFormBase { }Great, but there are still many to do … Captcha The Captcha will be assembled with: A dynamically generated image with a set of random numbers A TextBox control where the image number will be inserted A Validator control to validate whether TextBox numbers match the image numbers This is a common Captcha implementation, is not rocket science and don’t bring any additional problem. The main problem, as told before, is to find the correct anchor control to ensure a correct Captcha control injection. The anchor control can vary by: target control  theme Implementation To support this dynamic scenario I choose to use the following implementation:private List<string> _validAnchorIds = null; protected virtual List<string> ValidAnchorIds { get { if (this._validAnchorIds == null) { this._validAnchorIds = new List<string>(); this._validAnchorIds.Add("btnSubmit"); } return this._validAnchorIds; } } private Control GetAnchorControl(T wrapper) { if (this.ValidAnchorIds == null || this.ValidAnchorIds.Count == 0) { throw new ArgumentException("Cannot be null or empty", "validAnchorNames"); } var q = from anchorId in this.ValidAnchorIds let anchorControl = CSControlUtility.Instance().FindControl(wrapper, anchorId) where anchorControl != null select anchorControl; return q.FirstOrDefault(); } I can now, using the ValidAnchorIds property, configure a set of valid anchor control  Ids. The GetAnchorControl method searches for a valid anchor control within the set of valid control Ids. Here, some of you may question why to use a LINQ To Objects expression, but the important here is to notice the usage of CSControlUtility.Instance().FindControl CommunityServer method. I want to build on top of CommunityServer not to reinvent the wheel. Assuming that an anchor control was found, it’s now possible to inject the Captcha at the correct place. This not something new, we do this all the time when creating server controls or adding dynamic controls:protected sealed override void CreateChildControls() { base.CreateChildControls(); if (this.IsCaptchaRequired) { T wrapper = base.Control as T; if (wrapper != null) { Control anchorControl = GetAnchorControl(wrapper); if (anchorControl != null) { Panel phCaptcha = new Panel {CssClass = "CommonFormField", ID = "Captcha"}; int index = anchorControl.Parent.Controls.IndexOf(anchorControl); anchorControl.Parent.Controls.AddAt(index, phCaptcha); CaptchaConfiguration.DefaultProvider.AddCaptchaControls( phCaptcha, GetValidationGroup(wrapper, anchorControl)); } } } } Here you can see a new entity in action: a provider. This is a CaptchaProvider class instance and is only goal is to create the Captcha itself and do everything else is needed to ensure is correct operation.public abstract class CaptchaProvider : ProviderBase { public abstract void AddCaptchaControls(Panel captchaPanel, string validationGroup); } You can create your own specific CaptchaProvider class to use different Captcha strategies including the use of existing Captcha services  like ReCaptcha. Once the generic ControlAdapter was created became extremely easy to created a specific one. Here is the specific ControlAdapter for the WeblogPostCommentForm control:public class WeblogPostCommentFormCaptchaAdapter : WrappedFormBaseCaptchaAdapter<WrappedFormBase> { #region Overriden Methods protected override List<string> ValidAnchorIds { get { List<string> validAnchorNames = base.ValidAnchorIds; validAnchorNames.Add("CommentSubmit"); return validAnchorNames; } } protected override string DefaultValidationGroup { get { return "CreateCommentForm"; } } #endregion Overriden Methods } Configuration This is the magic step. Without changing the original pages and keeping the application original assemblies untouched we are going to add a new behavior to the CommunityServer application. To glue everything together you must follow this steps: Add the following configuration to default.browser file:<?xml version='1.0' encoding='utf-8'?> <browsers> <browser refID="Default"> <controlAdapters> <!-- Adapter for the WeblogPostCommentForm control in order to add the Captcha and prevent SPAM comments --> <adapter controlType="CommunityServer.Blogs.Controls.WeblogPostCommentForm" adapterType="NunoGomes.CommunityServer.Components.WeblogPostCommentFormCaptchaAdapter, NunoGomes.CommunityServer" /> </controlAdapters> </browser> </browsers> Add the following configuration to web.config file:<configuration> <configSections> <!-- New section for Captcha providers configuration --> <section name="communityServer.Captcha" type="NunoGomes.CommunityServer.Captcha.Configuration.CaptchaSection" /> </configSections> <!-- Configuring a simple Captcha provider --> <communityServer.Captcha defaultProvider="simpleCaptcha"> <providers> <add name="simpleCaptcha" type="NunoGomes.CommunityServer.Captcha.Providers.SimpleCaptchaProvider, NunoGomes.CommunityServer" imageUrl="~/captcha.ashx" enabled="true" passPhrase="_YourPassPhrase_" saltValue="_YourSaltValue_" hashAlgorithm="SHA1" passwordIterations="3" keySize="256" initVector="_YourInitVectorWithExactly_16_Bytes_" /> </providers> </communityServer.Captcha> <system.web> <httpHandlers> <!-- The Captcha Image handler used by the simple Captcha provider --> <add verb="GET" path="captcha.ashx" type="NunoGomes.CommunityServer.Captcha.Providers.SimpleCaptchaProviderImageHandler, NunoGomes.CommunityServer" /> </httpHandlers> </system.web> <system.webServer> <handlers accessPolicy="Read, Write, Script, Execute"> <!-- The Captcha Image handler used by the simple Captcha provider --> <add verb="GET" name="captcha" path="captcha.ashx" type="NunoGomes.CommunityServer.Captcha.Providers.SimpleCaptchaProviderImageHandler, NunoGomes.CommunityServer" /> </handlers> </system.webServer> </configuration> Conclusion Building a ControlAdapter can be complex but the reward is his ability to allows us, thru configuration changes, to modify an application render and/or behavior. You can see this ControlAdapter in action here and here (anonymous required). A complete solution is available in “CommunityServer Extensions” Codeplex project.

    Read the article

  • Converting listview to a composite control

    - by Paul
    The link below shows a listview composite control in its most basic form however I can't seem to extend this to what I'm trying to do. http://stackoverflow.com/questions/92689/how-to-define-listview-templates-in-code My listview has 1 tablerow with 2 fields. The first field contains 1 element whilst the second field contains 2 elements as shown below. <asp:ListView ID="lstArticle" runat="server"> <LayoutTemplate> <table id="itemPlaceholder" runat="server"> </table> </LayoutTemplate> <ItemTemplate> <div class="ctrlArticleList_rptStandardItem"> <table width="100%"> <tr> <td valign="top" class="ctrlArticleList_firstColumnWidth"> <a href="<%# GetURL(Container.DataItem) %>"> <%# GetImage(Container.DataItem)%> </a> </td> <td valign="top"> <span class="ctrlArticleList_title"> <a href="<%# GetURL(Container.DataItem) %>"> <%# DataBinder.Eval(Container.DataItem, "Title") %> </a> </span> <span class="ctrlArticleList_date"> <%# convertToShortDate(DataBinder.Eval(Container.DataItem, "ActiveDate"))%> </span> <div class="ctrlArticleList_standFirst"> <%# DataBinder.Eval(Container.DataItem, "StandFirst")%> </div> </td> </tr> </table> </div> </ItemTemplate> So to convert this I have to use the InstantiateIn method of the ITemplate for the layouttemplate and the ItemTemplate. Data is bound to the itemtemplate using the DataBinding event. My question at the moment is how do I setup the ItemTemplate class and bind the values from the above ListView ItemTemplate. This is what I've managed so far: private class LayoutTemplate : ITemplate { public void InstantiateIn(Control container) { var table = new HtmlGenericControl("table") { ID = "itemPlaceholder" }; container.Controls.Add(table); } } private class ItemTemplate : ITemplate { public void InstantiateIn(Control container) { var tableRow = new HtmlGenericControl("tr"); //first field in row var tableFieldImage = new HtmlGenericControl("td"); var imageLink = new HtmlGenericControl("a"); imageLink.ID = "imageLink"; tableRow.Controls.Add(imageLink); // second field in row var tableFieldTitle = new HtmlGenericControl("td"); var title = new HtmlGenericControl("a"); tableFieldTitle.Controls.Add(title); tableRow.Controls.Add(tableFieldTitle); //Bind the data with the controls tableRow.DataBinding += BindData; //add the controls to the container container.Controls.Add(tableRow); } public void BindData(object sender, EventArgs e) { var container = (HtmlGenericControl)sender; var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem; container.Controls.Add(new Literal() { Text = dataItem.ToString() }); } One of the functions in the ListView just for an example is: public string GetURL(object objArticle) { ArticleItem articleItem = (ArticleItem)objArticle; Article article = new Article(Guid.Empty, articleItem.ContentVersionID); return GetArticleURL(article); } Summary What do I need to do to convert the following into a composite control: 1. <a href="<%# GetURL(Container.DataItem) %>"><%# GetImage(Container.DataItem)%></a> 2. <a href="<%# GetURL(Container.DataItem) %>"> <%# DataBinder.Eval(Container.DataItem, "Title") %> </a>

    Read the article

  • ASP.NET 4.0 UpdatePanel and UserControl with PlaceHolder

    - by Chris
    I don't know if this is ASP.NET 4.0 specific but I don't recall having this problem in previous versions. I have very simple user control called "TestModal" that contains a PlaceHolder control which I use to instantiate a template in. When I put an UpdatePanel inside this UserControl on the page the updatepanel only does full postbacks and not partial postbacks. What gives? USER CONTROL MARKUP: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestModal.ascx.cs" Inherits="MyProject.UserControls.TestModal" %> <div id="<%= this.ClientID %>"> <asp:PlaceHolder ID="plchContentTemplate" runat="server"></asp:PlaceHolder> </div> USER CONTROL CODE BEHIND: public partial class TestModal : System.Web.UI.UserControl { private ITemplate _contentTemplate; [TemplateInstance(TemplateInstance.Single)] [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(TemplateControl))] public ITemplate ContentTemplate { get { return _contentTemplate; } set { _contentTemplate = value; } } protected override void OnInit(EventArgs e) { base.OnInit(e); if (_contentTemplate != null) _contentTemplate.InstantiateIn(plchContentTemplate); } } ASPX PAGE MARKUP: <ajaxToolkit:ToolkitScriptManager ID="scriptManager" EnablePartialRendering="true" AllowCustomErrorsRedirect="true" CombineScripts="true" EnablePageMethods="true" ScriptMode="Release" AsyncPostBackTimeout="180" runat="server"></ajaxToolkit:ToolkitScriptManager> <uc1:TestModal ID="testModal" ClientIDMode="Static" runat="server"> <ContentTemplate> <asp:UpdatePanel ID="upAttachments" UpdateMode="Conditional" ChildrenAsTriggers="true" runat="server"> <ContentTemplate> <asp:LinkButton ID="lnkRemoveAttachment" runat="server"><img src="/images/icons/trashcan.png" style="border: none;" /></asp:LinkButton> </ContentTemplate> </asp:UpdatePanel> </ContentTemplate> </uc1:TestModal>

    Read the article

  • How to build a GridView like DataBound Templated Custom ASP.NET Server Control

    - by Deyan
    I am trying to develop a very simple templated custom server control that resembles GridView. Basically, I want the control to be added in the .aspx page like this: <cc:SimpleGrid ID="SimpleGrid1" runat="server"> <TemplatedColumn>ID: <%# Eval("ID") %></ TemplatedColumn> <TemplatedColumn>Name: <%# Eval("Name") %></ TemplatedColumn> <TemplatedColumn>Age: <%# Eval("Age") %></ TemplatedColumn> </cc:SimpleGrid> and when providing the following datasource: DataTable table = new DataTable(); table.Columns.Add("ID", typeof(int)); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Age", typeof(int)); table.Rows.Add(1, "Bob", 35); table.Rows.Add(2, "Sam", 44); table.Rows.Add(3, "Ann", 26); SimpleGrid1.DataSource = table; SimpleGrid1.DataBind(); the result should be a HTML table like this one. ------------------------------- | ID: 1 | Name: Bob | Age: 35 | ------------------------------- | ID: 2 | Name: Sam | Age: 44 | ------------------------------- | ID: 3 | Name: Ann | Age: 26 | ------------------------------- The main problem is that I cannot define the TemplatedColumn. When I tried to do it like this ... private ITemplate _TemplatedColumn; [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer(typeof(TemplatedColumnItem))] [TemplateInstance(TemplateInstance.Multiple)] public ITemplate TemplatedColumn { get { return _TemplatedColumn; } set { _TemplatedColumn = value; } } .. and subsequently instantiate the template in the CreateChildControls I got the following result which is not what I want: ----------- | Age: 35 | ----------- | Age: 44 | ----------- | Age: 26 | ----------- I know that what I want to achieve is pointless and that I can use DataGrid to achieve it, but I am giving this very simple example because if I know how to do this I would be able to develop the control that I need. Thank you.

    Read the article

  • How can I include additional markup within a 'Content' inner property within an ASP.Net WebControl?

    - by GenericTypeTea
    I've searched the site and I cannot find a solution for my problem, so apologies if it's already been answered (I'm sure someone must have asked this before). I have written a jQuery Popup window that I've packaged up as a WebControl and IScriptControl. The last step is to be able to write the markup within the tags of my control. I've used the InnerProperty attribute a few times, but only for including lists of strongly typed classes. Here's my property on the WebControl: [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public something??? Content { get { if (_content == null) { _content = new something???(); } return _content; } } private something??? _content; Here's the HTML Markup of what I'm after: <ctr:WebPopup runat="server" ID="win_Test" Hidden="false" Width="100px" Height="100px" Modal="true" WindowCaption="Test Window" CssClass="window"> <Content> <div style="display:none;"> <asp:Button runat="server" ID="Button1" OnClick="Button1_Click" /> </div> <%--Etc--%> <%--Etc--%> </Content> </ctr:WebPopup> Unfortunately I don't know what type my Content property should be. I basically need to replicate the UpdatePanel's ContentTemplate. EDIT: So the following allows a Template container to be automatically created, but no controls show up, what's wrong with what I'm doing? [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ITemplate Content { get { return _content; } set { _content = value; } } private ITemplate _content;

    Read the article

  • SharePoint and COMException (0x80004005): Cannot complete this action

    - by Damon
    I ran into a small issue today working on a deployment.  We were moving a custom ASP.NET control from my development environment into a SharePoint layout page on a staging environment .  I was expecting some minor issues to arise since I had developed the control in an ASP.NET website project, but after getting everything moved over we got an obscure COMException error the that looked like this: Cannot complete this action. Please try again. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: Cannot complete this action. [COMException (0x80004005): Cannot complete this action. .Lengthy stack trace goes here. Everything in the custom control was built using managed code, so we weren't sure why a COMException would suddenly appear. The control made use of an ITemplate to define its UI, so there was a lot of markup and binding code inside the template. As such, we started taking chunks of the template out of the layout page and eventually the error went away.  It was being caused by a section of code where we were calling a custom utility method inside some binding code: <%# WebUtility.FormatDecimal(.) %> Solution: It turns out that we were missing an Assembly and Import directive at the top of the page to let the page know where to find this method.  After adding these to the page, the error went away and everything worked great.  So a COMException (0x80004005) Cannot complete this action error is just SharePoint's friendly way of letting you know you're missing an assembly or imports reference.

    Read the article

  • RenderControl error

    - by Rubans
    HI, I have a grid with which I'm templating columns with and one column is a user control. Since I'm adding these in the code behind ( using ITemplate), I get an error when I try to render the UserControl. This particular user control does require a scriptmanager since it includes a ajax control (radcombobox). The error I get is : Script control 'LookupComboBox' is not a registered script control. Script controls must be registered using RegisterScriptControl() before calling RegisterScriptDescriptors(). I'm not sure even if my approach is correct using user control and using RenderControl.

    Read the article

  • ASP.NET Custom Control - Default Template?

    - by Bob Fincheimer
    I know this is really picky, but can I have one template inside a user control: <uc:MyUserControl runat="server" ID="test"> <div><b>Test</b></div> <asp:PlaceHolder runat="server" id="pH" /> </uc:MyUserControl> Instead of what I have now which requires me to: <uc:MyUserControl runat="server" ID="test"> <Content> <div><b>Test</b></div> <asp:PlaceHolder runat="server" id="pH" /> </Content> </uc:MyUserControl> Basically I want my control to have only one ITemplate inside of it.

    Read the article

  • insert DropDownList and TextField in Gridview

    - by userk
    HI,I need to create a GridView which DataSource is an object. Depending on the object I may need some columns with DropDownLists or TextFields (but not all rows) As I don't know the number or columns, they have to be dynamic. I found this solution: TemplateField t = new TemplateField(); t.HeaderTemplate = new GridViewTemplate("header", "title"); t.ItemTemplate = new GridViewTemplate("combobox", "val"); GridView1.Columns.Add(t); GridView1.DataSource = ds; GridView1.DataBind(); Where GridViewTemplate extends ITemplate. This didn't work for me, it fills all rows of a column and I had no way to control witch DropDownList and TextFields need to be created (object info). All the DropDownLists need to have an ID also only known by the object. There are some way I can do this?

    Read the article

  • An Unusual UpdatePanel

    - by João Angelo
    The code you are about to see was mostly to prove a point, to myself, and probably has limited applicability. Nonetheless, in the remote possibility this is useful to someone here it goes… So this is a control that acts like a normal UpdatePanel where all child controls are registered as postback triggers except for a single control specified by the TriggerControlID property. You could basically achieve the same thing by registering all controls as postback triggers in the regular UpdatePanel. However with this, that process is performed automatically. Finally, here is the code: public sealed class SingleAsyncTriggerUpdatePanel : WebControl, INamingContainer { public string TriggerControlID { get; set; } [TemplateInstance(TemplateInstance.Single)] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate ContentTemplate { get; set; } public override ControlCollection Controls { get { this.EnsureChildControls(); return base.Controls; } } protected override void CreateChildControls() { if (string.IsNullOrWhiteSpace(this.TriggerControlID)) throw new InvalidOperationException( "The TriggerControlId property must be set."); this.Controls.Clear(); var updatePanel = new UpdatePanel() { ID = string.Concat(this.ID, "InnerUpdatePanel"), ChildrenAsTriggers = false, UpdateMode = UpdatePanelUpdateMode.Conditional, ContentTemplate = this.ContentTemplate }; updatePanel.Triggers.Add(new SingleControlAsyncUpdatePanelTrigger { ControlID = this.TriggerControlID }); this.Controls.Add(updatePanel); } } internal sealed class SingleControlAsyncUpdatePanelTrigger : UpdatePanelControlTrigger { private Control target; private ScriptManager scriptManager; public Control Target { get { if (this.target == null) { this.target = this.FindTargetControl(true); } return this.target; } } public ScriptManager ScriptManager { get { if (this.scriptManager == null) { var page = base.Owner.Page; if (page != null) { this.scriptManager = ScriptManager.GetCurrent(page); } } return this.scriptManager; } } protected override bool HasTriggered() { string asyncPostBackSourceElementID = this.ScriptManager.AsyncPostBackSourceElementID; if (asyncPostBackSourceElementID == this.Target.UniqueID) return true; return asyncPostBackSourceElementID.StartsWith( string.Concat(this.target.UniqueID, "$"), StringComparison.Ordinal); } protected override void Initialize() { base.Initialize(); foreach (Control control in FlattenControlHierarchy(this.Owner.Controls)) { if (control == this.Target) continue; bool isApplicableControl = false; isApplicableControl |= control is INamingContainer; isApplicableControl |= control is IPostBackDataHandler; isApplicableControl |= control is IPostBackEventHandler; if (isApplicableControl) { this.ScriptManager.RegisterPostBackControl(control); } } } private static IEnumerable<Control> FlattenControlHierarchy( ControlCollection collection) { foreach (Control control in collection) { yield return control; if (control.Controls.Count > 0) { foreach (Control child in FlattenControlHierarchy(control.Controls)) { yield return child; } } } } } You can use it like this, meaning that only the B2 button will trigger an async postback: <cc:SingleAsyncTriggerUpdatePanel ID="Test" runat="server" TriggerControlID="B2"> <ContentTemplate> <asp:Button ID="B1" Text="B1" runat="server" OnClick="Button_Click" /> <asp:Button ID="B2" Text="B2" runat="server" OnClick="Button_Click" /> <asp:Button ID="B3" Text="B3" runat="server" OnClick="Button_Click" /> <asp:Label ID="LInner" Text="LInner" runat="server" /> </ContentTemplate> </cc:SingleAsyncTriggerUpdatePanel>

    Read the article

  • Usercontrol losing Viewstate across Postback

    - by Robert W
    I have a user control which uses objects as inner properties (some code is below). I am having trouble with setting the attribute of the Step class programmatically, when set programmatically it is being lost across postback which would indicate something to do with Viewstate (?). When setting the property of the Step class declaratively it's working fine. Does anybody have any ideas of what this code be/what's causing it to lose the state across postback? public partial class StepControl : System.Web.UI.UserControl { [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [NotifyParentProperty(true)] public Step Step1 { get; set; } [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [NotifyParentProperty(true)] public Step Step2 { get; set; } protected void Page_Init(object sender, EventArgs e) { AddSteps(); } private void AddSteps() { } } [Serializable()] [ParseChildren(true)] [PersistChildren(false)] public class Step { [PersistenceMode(PersistenceMode.Attribute)] public string Title { get; set; } [PersistenceMode(PersistenceMode.Attribute)] public string Status { get; set; } [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateInstance(TemplateInstance.Single)] [TemplateContainer(typeof(StepContentContainer))] public ITemplate Content { get; set; } public class StepContentContainer : Control, INamingContainer { } }

    Read the article

1 2  | Next Page >