Best way to start building a custom-rendered control? - asp.net

I am needing to create a custom control.
Basically, I'm wishing to create a light weight(and better using jquery) Accordion control.
What are some good references for getting started with doing such a thing. I will be deriving it from a Panel because it's very similar(just needs a bit of JS tacked onto the end) but I want it to only be able to add controls of a certain type. I'm having trouble finding any information about custom rendered controls.
Can anyone point me to some references? Also, for the ID tag in HTML, would you use UniqueID or ClientID?

Any good ASP.NET book should have a chapter devoted to custom controls. If all you wanted to do was add some JS to Panel I would think you could just do this:
public class AccordianPanel : System.Web.UI.WebControls.Panel
{
protected override void OnPreRender(EventArgs e)
{
base.Render(writer);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "accordianscript", ScriptText);
}
}
Or create a User Control with nothing but a Panel and the javascript in the ascx. Limiting the allowed controls is problematic at best...
As for the ID, always use ClientID to reference controls in client-side script.

I would consider using the AjaxControlToolkit, and look at the documentation there (on asp.net) for how to use that to create a custom control or extender. That makes it easy to create custom controls, and you can embed JQuery in those components. The ACT provides all the plumbing; there is less work for you to use the MS ajax framework and link everything together.
I've used it and it works well, though I must admit I've recently scrapped it for my set of AJAX components within my custom framework (http://www.codeplex.com/nucleo). That was for other reasons.

I missed part of your question; to validate for allowing only certain controls, you can override the AddedControl method, which is called when the control gets added. You can validate control types in this method.
Or, most controls implement a custom control collection, and I believe there is a CreateControlCollection that you can use to create a custom control. This custom control collection validates the control within the Add/AddAt method.

Related

What is the correct ASP.NET Control event/method in which to add nested controls?

What is the correct event/method in the ASP.NET life cycle to dynamically add Child Controls ?
My objective is to ensure that all the input controls on a User Control have the correct associated Validator and Label controls, based on configuration from an external file.
It seems like the correct place should be either OnInit(EventArgs e) or CreateChildControls(). Both of them are behaving a little bit unexpected, and rather than try to debug each of them, I figured I'd first ask you guys which one (or other) to use.
Its OnInit, and you need to do it on first load and on post back.
Since this is a Web User Control (ASCX) create the dynamic controls during OnInit. By creating them during OnInit they will be created on the first page load and on every postback.
The CreateChildControls method is typically used for rendering in custom server controls.

How to change html view of web user control

I am creating a web user control for a simple poll. I am currently registering it on the page and then referencing it via tagprefix.
The form for the poll is in basic html (no server controls) and is in the front-end of the web control. How can I change the look of the user control depending on the settings passed into it? Is this possible without using server controls?
Update
Can I change the html layout of a user control? If so could someone post some examples. Please note I do not use asp.net form controls, so none of that please :)
You might be able to also use jQuery to replace existing css setting in your code. Create properties on for your user control, and then pass settings in the classes. Then use jQuery to replace them. This however requires jQuery to be linked to your page (or within your control) and you'd have to write the CSS classes out to the jQuery code (using server controls, but you could use the literal control so there's no excess code).
Personally I'd go with the option of using server controls instead of straight up HTML, you'd get alot more flexibility, and then passing through the settings would be pretty straightforward, put something like this in your controls backend code:
Private _TextBoxCssClass As String
Public Property TextBoxCssClass() As String
Get
Return _TextBoxCssClass
End Get
Set(ByVal value As String)
_TextBoxCssClass = value
txtBox1.CssClass = value
txtBox2.CssClass = value
End Set
End Property
You most likely want to have a property or event in the control that changes the css. It may end up best to add some server controls or javascript / jquery to make it easier.
If its only the styles you want to change, then you can expose a property to set the style attribuites of the respective control inside your User Control. If you want to control the whole HTML layout of the control then Custom Control is the viable option.

Custom TextBox Control with built-in client-side validation

I have a textbox in my application which has multiple validation on it e.g. RequiredFieldValidator, RegexValidation and CustomValidation. My page has several similar textboxes. So I just copy-paste and change id and controltovalidate properties and it is working.
Since similar tbxs are going to be used on another page as well, I think it would be nice to create my own custom TextBox control with built-in validation.
Here are two approaches I have found and tried:
1: Implement from IValidator perform my custom validation in Validate Method. As shown here: Self-Validating TextBox But it does not show how to implement client-side validation.
2: Create custom control that derives from TextBox and add asp.net built-in validators I need. As shown here:Custom TextBox. I tried the code and it works server/client side.
I like the first approach but don't know how to implement client-side validation. I know I need a client-side js function. I can do that. I know how to include my js file using Page.ClientScript class but don't know how to integrate all together and make it work.
I can create a UserControl or the second approach above but for now I am specifically looking to learn and implement client-side validation from custom control.
I am using Asp.Net 2.0. Thanks for any suggestions.
Well, you're right, you can always implement your custom server control that derives from TextBox and automatically associates a couple of validators. But usually you won't create custom controls as far as it is not explicitly needed and then through several different projects. For having client-side validaton you usually need JavaScript, but note that most of the ASP.net validation controls have their client-side validation already built-in (i.e. required field validators, range validators,...). Others (like the custom validator) allow to hook in your custom javascript.
An approach that sounds more reasonable to me is to have your TextBox controls as they are on your ASP.net page/usercontrol and to associate the validators from your code dynamically at runtime. Say in your OnInit event, you call a function RegisterRequiredValidators passing in a list of TextBoxes. I'm just thinking aloud:
public override void OnInit(...)
{
...
RegisterRequiredValidators(
txtFirstname,
txtSurname,
txtAge
}
...
}
public void RegisterRequiredValidators(params Control[] textBoxes)
{
//execute the logic of creating and attaching validators
}
That's just a stupid example, just to explain the context. In theory you can evolve this concept to register any kind of validators. We do something similar at work, by abstracting this in form of "rules" which ultimately are being rendered as ASP.net validators on the front-end.

Dynamic adding controls during OnLoad or OnInit?

I want to add more controls to page based on some specific conditions. Those controls don't need any ViewState or binding data, it is as simple as a static link.
I wonder where I could write the code: inside OnLoad or OnInit method? and why? If I place it inside OnLoad, should I add following line: if (IsPostBack) return; before any initialization code?
You can add controls in either the OnInit method or OnLoad, whether they need view state or not. (The reason why is because as soon as you add a control to the Page the control loads its view state, even if you add it after the LoadViewState stage...)
should I add following line: if (IsPostBack) return; before any initialization code?
No. It is imperative that your dynamically added controls are added to the control hierarchy on every page load, not just the initial one.
If you are going to work with dynamically-added Web controls, I strongly suggest you read these two articles:
Dynamic Controls in ASP.NET (This is actually three articles, this being the first in a series.)
Creating Dynamic Data Entry User Interfaces
For a working, end-to-end example of dynamically loading controls based on some external conditions (such as configuration in a database), see Creating a Dynamic Data-Driven User Interface.
Happy Programming!
I would suggest just adding the controls to the page statically and toggling their visibility to "True" when the conditions are met. They won't render anything to the page when they're invisible, and this will save you a lot of headaches, especially since it sounds like you're fairly new to dynamic controls.
I'm not sure I fully understand, but I'd personally put an asp:Literal on the page (or several if you need them in different places) and then create the HTML you need in the OnLoad event.
If you do that, then the html you put into that literal will be saved in viewstate, and therefor you won't have redo it on postback.
http://chetanwarade.wordpress.com/2010/08/21/asp-net-add-dynamic-control-and-retrieve-dynamic-control-value-2/
Here is code that demonstrate how to add dynamic control and retrieve dynamic control value.

How To: Use AJAX in an ASP.NET Custom Server Control

Does anyone know of a good tutorial that demonstrates using an existing AJAX control extender in a Custom ASP.NET Server Control?
I do not want to build a "Custom AJAX Server Control". I want to build a Custom Server Control that uses an existing AJAX control extender.
I would like to combine an asp:TextBox, asp:ImageButton, asp:CustomValidator (with client side javascript from an embedded resource), and an ajax:CalendarExtender into one custom server control. Or has this already been created?
Any help would be greatly appreciated. Thanks.
UPDATE: Basically, I would like to create a CompositeControl that has an ajax:CalendarExtender as a child control.
Sounds like what you're after is a composite control. They are pretty much exactly like a user control only instead of using the ascx file to create the controls you create them all programmatically. The big advantage of doing this over using a user control is you end up with something you can put in an assembly and use in different projects.
A composite control can inherit from either Control or WebControl. I personally usually find Control more useful to inherit from because I usually don't need a lot of the extra stuff you get from WebControl such as the styling properties since I usually just style through a single CssClass property.
You'll also need to make sure your class implements the INamingContainer interface. This will make sure that each child control will automatically get a unique name if the control is used multiple times in the same parent container.
The most important thing to do when creating a composite control is to override Control's CreateChildControls method. All the logic for actually creating the controls should go in here. The framework will automatically make sure that this gets called at the right time in the page lifecycle.
Here's a little example:
public class MyCompositeControl : Control, INamingContainer
{
protected override void CreateChildControls()
{
Controls.Clear();
var textbox = new TextBox();
textbox.ID = "TextBox1";
Controls.Add(textbox);
if (!Page.IsPostBack || !IsTrackingViewState)
{
// make sure you set the properties after
// you add it to the parent or the viewstate
// won't save properly
textbox.MaxLength = 30;
}
var button = new Button();
button.ID = "Button1";
Controls.Add(button);
if (!Page.IsPostBack || !IsTrackingViewState)
{
button.Text = "Save";
}
}
}
I don't think ASP.NET AJAX should complicate this much. The only thing I can think of ist you'll need to make sure that you create a ScriptManager on whatever page the composite control will be added to.
There's a full example of this on the MSDN site. There's another nice example on this blog.
What you want is to build a user control and not a custom control most probably. A user control is a composite control whereas a custom control is a control built either from the ground up either derived from a basic control.
I would suggest you search on MSDN. I have seen several good articles about that topic in their magazines over the last year or two, that have been fairly thorough. But I don't have links to them and I'm too lazy to Google for you. :\

Resources