|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionIn this article we will have a look at implementing a custom web control. This web control will inherit from the TextBox web control, and will automatically add a required field validator at run-time. This way, when we need a required field text box, we don't need to mess about with the required field validator, but instead we just define an instance of our custom web control. Class definitionThe class definition for our web control is quite straightforward. Since we want to create a TextBox control, we will inherit from the TextBox class. This means we will still be able to use all of the existing attributes which are defined for the TexBox - after all, we want a texbox as the basis with a required field validator 'embedded'. Let's have a look at our code-behind file for our RequiredTextBox control.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WimdowsControls.Web.UI {
public class RequiredTextBox : TextBox {
private RequiredFieldValidator req;
public string InvalidMessage;
public string ClientScript="true";
protected override void OnInit(EventArgs e) {
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = this.InvalidMessage;
req.EnableClientScript = (this.ClientScript.ToLower()!="false");
Controls.Add(req);
}
protected override void Render(HtmlTextWriter w) {
base.Render(w);
req.RenderControl(w);
}
}
}
As we can see, we define the class csc /out:bin\wimdowscontrols.dll /target:library /r:system.dll wimdowscontrols.cs
Now, let's see what our cool ASP.NET page looks like: <%@ Register TagPrefix="Wimdows" Namespace="WimdowsControls.Web.UI"
Assembly="WimdowsControls" %>
<form runat="server">
<Wimdows:RequiredTextBox runat="server" id="txtName"
InvalidMessage="Name is required."
ClientScript="false"/>
<br />
<asp:Button runat="server" id="btnSubmit" Text="Validate"/>
</form>
That's it! We need do need the Register directive to register our component, almost in the same way as we do with a user control. Whereas the user control would point to a Src .ascx file, we specifiy our namespace in which we declared our custom control and the physical assembly, the DLL. By using any
You will notice that on the submit of the form, it will always perform a server round-trip, because we explicitly specified the ClientScript attribute value to false. ConclusionIn this article we've briefly seen how beneficial it can be to create your own composite custom control. Of course you can extend the sample by adding more controls, and more attributes - but I will leave that up to you. You know the basics now!
|
||||||||||||||||||||||