Toars I will smile to the world ^o^

24Sep/092

How to access the sub controls in the PagerTemplate in DataPager .NET control

At least for me, I can not use MyDataPage.FindControl("LblPage") to find my LblPage control in the PagerTemplate.

I have to use an recursive way to locate it.

        public static Control FindControlRecursive(Control container, string id)
        {
            if (container.ID == id)
                return container;

            foreach (Control control in container.Controls)
            {
                Control foundControl = FindControlRecursive(control, id);

                if (foundControl != null)
                    return foundControl;
            }

            return null;
        }
Tagged as: 2 Comments
14Sep/095

How to Set or Change the HeadText values in GridView control

GridView control offers us to bind the data and list the data in columns with nice format. However, when I want bind the HeadText properties for the columns of the data, I have to use this way:
--------------------------------------------------------------------------------

MyGridView.Columns[0].HeadText = "Head Text For Column 1";
MyGridView.Columns[1].HeadText = "Head Text For Column 2";

--------------------------------------------------------------------------------
Just FYI, *_*

Filed under: .NET, C#, Miscellaneous 5 Comments
9Sep/094

AjaxControlToolKit : ConfirmButtonExtender and ModalPopupExtender

Will do it later

4Sep/094

The CustomValidator and the EventHandler ServerValidateEventArgs / Customized TextBox control

This is more like a continuous article to the previous post.

In this article, I am going to explain a bit how to intergreate the CustomValidator and the ServerValidEventArgs event handler into the TextBox control, and after the integration, you don't need to explicitly have a CustomValidator and the ServerValidEventArgs in the Aspx page, all you need to do is to create a ServerValidEventArgs event for the instance of TextBox control and the CustomValidator will be created accordingly automatically by the TextBox control.

In this example, OTextBox is the customized version of TextBox that integrated with a CustomValidator and its ServerValidEventArgs.

Here is the code for: OTextBox.cs

public class OTextBox : System.Web.UI.WebControls.TextBox
{
    // This is the CustomValidator that will be added to the OTextBox instance if its
    // server validate event handler is created by the user.
    private CustomValidator _customValidator;

    // The server validate event handler.
    public event EventHandler CustomServerValidate;

    /// <summary>
    /// Called by the ASP.NET page framework to notify server controls that
    /// use composition-based implementation to create any child controls
    /// they contain in preparation for posting back or rendering.
    /// </summary>
    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        //CustomValidator
        _customValidator = new CustomValidator();
        _customValidator.ID = "CustomValidator" + this.ID;
        _customValidator.ControlToValidate = this.ID;
        _customValidator.Display = ValidatorDisplay.None;
        _customValidator.ErrorMessage = "Error Message for CustomValidator";
        _customValidator.ServerValidate += new ServerValidateEventHandler(_customValidator_SV);

        // Add the CustomValidator to the page
        Controls.Add(_customValidator);
    }

    /// <summary>
    /// Handles the ServerValidate event of the _customValidator control.
    /// </summary>
    /// <param name="source">The source of the event.</param>
    /// <param name="args">The instance containing the event data.</param>
    private void _customValidator_SV(object source, ServerValidateEventArgs args)
    {
        // If this server validate event handler has been created by the user
        if (CustomServerValidate != null)
            CustomServerValidate(source, args);
    }

    /// <summary>
    /// Outputs server control content to a provided  object and stores
    /// tracing information about the control if tracing is enabled.
    /// </summary>
    /// <param name="writer">The object that receives the control content.</param>
    public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
    {
        base.RenderControl(writer);

        // Render the CustomValidator
        if (this.CustomServerValidate != null)
            _customValidator.RenderControl(writer);
    }
}

How to use this customized control? Very simple, here is another example:

Assume that the OTextBox's namespace is Example.Mycontrols, so add the section below to the Web.Config file in order to access the customized control as <uc:ControlName ID="Balala" runat="server" />:

<pages>
    <controls>
        <add tagPrefix="uc" namespace="Example.MyControls" assembly="Example"/>
    </controls>
</pages>

And in Default.aspx page, add the OTextBox instance:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Example.Default" %>
<html>
<head id="Head" runat="server" />
<title></title>
<body>
    <form id="DefaultForm" runat="server">
        <uc:OTextBox ID="TxtExample" runat="server" />
    </form>
</body>
</html>

In Default.aspx.cs code-behind, create the event handler, and associate it with a method:

namespace Example
{
    public partial class Default : System.Web.UI.Page
    {
        /// <summary>
        /// Raises the event to initialize the page.
        /// </summary>
        /// <param name="e">An EventArgs that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            TxtExample.CustomServerValidate += new EventHandler(TxtExample_CustomServerValidate);
        }

        /// <summary>
        /// Handles the CustomServerValidate event of the TxtEmailAddress control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        public void TxtExample_CustomServerValidate(object sender, ServerValidateEventArgs e)
        {
            if (Something is OK)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
    }
}

Then it is done, isn't that simple, and you can add some code to this TxtExample_CustomServerValidate method, and it will validate it when Page.Validate() occurs, is that cool?

Thanks!

3Sep/096

My customized TextBox control with various validators integrated, is it convenient for you as well?

It is so boring that when every time i create a form that need to be filled in by the user, for example, the Password field, and Re-Password field, E-mail Address field and Comfirm E-mail Address field, i need to create the RequiredFieldValidator, RegularExpressionValidator, and CompareValidator for each of them. That is really messy and redundent for the Aspx pages.

So, I am thinking about to customize the default TextBox control and write a my own OTextBox control with all the three validators integrated inside the OTextBox.

By doing this, OTextBox can enable me, if I want an OTextBox instance that need to have the regular expression to validate its input before submit, just set its ValidateRegularExpression propertity to a pre-defined RegularExpressionType, and nothing more to add in the Aspx pages.

Here is the code:
--------------------------------------------------------------------------------
OTextBox.cs

public class OTextBox : System.Web.UI.WebControls.TextBox
{
    private RequiredFieldValidator _requiredValidator;
    private CompareValidator _compareValidator;
    private RegularExpressionValidator _regularValidator;

    // ValidatorCalloutExtender is a pop up box with the error message when the error occurs
    // with its validator and this ValidatorCalloutExtender is from AjaxControlToolkit.
    private ValidatorCalloutExtender _requiredCalloutExtender;
    private ValidatorCalloutExtender _compareCalloutExtender;
    private ValidatorCalloutExtender _regularCalloutExtender;

    /// <summary>
    /// If this propertity is set to true, then the RequiredFieldValidator
    /// will be added and validate the text field in current control.
    /// </summary>
    public bool Required
    {
        set{ this.ViewState["Required"] = value; }
        get
        {
             if (this.ViewState["Required"] != null)
                 return (bool)this.ViewState["Required"];
             return false;
        }
    }

    /// <summary>
    /// If this propertity is set to a value, then the CompareValidator
    /// will be added and compare the text field in current control
    /// to the control that is given by this propertity.
    /// </summary>
    public string CompareToTextBoxID
    {
        set{ this.ViewState["CompareToTextBoxID"] = value; }
        get
        {
             if (this.ViewState["CompareToTextBoxID"] != null)
                 return (string)this.ViewState["CompareToTextBoxID"];
             return string.Empty;
        }
    }

    /// <summary>
    /// If this propertity is set to a value, then the CompareValidator
    /// will be added and compare the text field in current control
    /// to the control that is given by this propertity.
    /// </summary>
    public RegularExpressionType ValidateRegularExpression
    {
        set{ this.ViewState["ValidateRegularExpression"] = value; }
        get
        {
             if (this.ViewState["ValidateRegularExpression"] != null)
                 return (RegularExpressionType)this.ViewState["ValidateRegularExpression"];
             return RegularExpressionType.None;
        }
    }

    /// <summary>
    /// Nothing much, the constructor.
    /// </summary>
    public void OTextBox
    {
        // Can put something here
    }

    /// <summary>
    /// will create all the necessary controls and add them to the Controls collection
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        // For RequiredValidator
        if (this.Required)
        {
            _requiredValidator = new RequiredFieldValidator();
            _requiredValidator.ControlToValidate = this.ID;
            _requiredValidator.ID = "RequiredValidator" + this.ID;
            _requiredValidator.Display = ValidatorDisplay.None;
            _requiredValidator.ErrorMessage = "Your Error Message For RequiredValidator";

            _requiredCalloutExtender = new ValidatorCalloutExtender();
            _requiredCalloutExtender.TargetControlID = _requiredValidator.ID;
            _requiredCalloutExtender.ID = "RequiredCallout" + this.ID;
            _requiredCalloutExtender.HighlightCssClass = "YourCssForThisPopUp";
            _requiredCalloutExtender.Width = 100; // The width you want this pop to be

            Controls.Add(_requiredValidator);
            Controls.Add(_requiredCalloutExtender);
        }

        // For CompareValidator
        if (!string.IsNullOrEmpty(this.CompareToTextBoxID))
        {
            OTextBox txtBoxNeedToCompare = (OTextBox)this.Parent.FindControl(this.CompareToTextBoxID);
            if (txtBoxNeedToCompare != null)
            {
                 _compareValidator = new CompareValidator();
                 _compareValidator.ControlToValidate  = this.ID;
                 _compareValidator.ControlToCompare = this.CompareToTextBoxID;
                 _compareValidator.ID = "CompareValidator" + this.ID;
                 _compareValidator.Display = ValidatorDisplay.None;
                 _compareValidator.ErrorMessage = "Your Error Message For CompareValidator";

                 _compareCalloutExtender = new ValidatorCalloutExtender();
                 _compareCalloutExtender.TargetControlID = _compareValidator.ID;
                 _compareCalloutExtender.ID = "CompareCallout" + this.ID;
                 _compareCalloutExtender.HighlightCssClass = "YourCssForThisPopUp";
                 _compareCalloutExtender.Width = 100; // The width you want this pop to be

                 Controls.Add(_compareValidator);
                 Controls.Add(_compareCalloutExtender);
            }
        }

        // For RegularExpressionValidator
        if (this.ValidateRegularExpression != RegularExpressionType.None)
        {
            _regularValidator = new RegularExpressionValidator();
            _regularValidator.ControlToValidate = this.ID;
            _regularValidator.ID = "RegularExpressionValidator" + this.ID;
            _regularValidator.Display = ValidatorDisplay.None;
            _regularValidator.ErrorMessage = "Your Error Message For RegularExpressionValidator";

            switch(ValidateRegularExpression)
            {
                 case RegularExpressionType.Email:
                     _regularValidator.ValidationExpression = "Your regular express for email";
                     break;
                 case RegularExpressionType.Domain:
                     _regularValidator.ValidationExpression = "Your regular express for domain";
                     break;
                 case RegularExpressionType.PhoneNumber:
                     _regularValidator.ValidationExpression = "Your regular express for phone number";
                     break;
                // Can add more if needed.
            }

            _regularCalloutExtender = new ValidatorCalloutExtender();
            _regularCalloutExtender.TargetControlID = _regularValidator.ID;
            _regularCalloutExtender.ID = "RegularCallout" + this.ID;
            _regularCalloutExtender.HighlightCssClass = "YourCssForThisPopUp";
            _regularCalloutExtender.Width = 100; // The width you want this pop to be

            Controls.Add(_regularValidator);
            Controls.Add(_regularCalloutExtender);
        }
    }

    /// <summary>
    /// Render these controls
    /// </summary>
    public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
    {
        base.RenderControl(writer);

        // For RequiredValidator
        if (this.Required)
        {
            _requiredValidator.RenderControl(writer);
            _requiredCalloutExtender.RenderControl(writer);
        }

        // For CompareValidator
        if (!string.IsNullOrEmpty(this.CompareToTextBoxID))
        {
            OTextBox txtBoxNeedToCompare = (OTextBox)this.Parent.FindControl(this.CompareToTextBoxID);
            if (txtBoxNeedToCompare != null)
            {
                _compareValidator.RenderControl(writer);
                _compareCalloutExtender.RenderControl(writer);
            }
        }

        // For RegularExpressionValidator
        if (this.ValidateRegularExpression != RegularExpressionType.None)
        {
            _regularValidator.RenderControl(writer);
            _regularCalloutExtender.RenderControl(writer);
        }
    }
}

RegularExpressionType.cs

public enum RegularExpressionType
{
    None = 0,
    Email = 1,
    PhoneNumber = 2
}

--------------------------------------------------------------------------------

I only showed an example of how to customize the TextBox control, actually, there are still a lot of useful functionalities that can be integrated, such as ValidationGroup, and other extra stuff that can be extended to the default TextBox control.

Hope this article can help someone and reduce the amount of work.

2Sep/091

Customized WebBrowser control

WebBroswer control which is introduced since .Net 2.0 enables us to have a web browser in our application easily. When I use it, I encountered some issues that can not be handled by the default WebBrowser. For example, It does not have enough events for certain situations, such the event DocumentComplete, nor enough functionalities that as the regular browsers do, such block unwanted pop ups.

Will continue on this post later today or tomorrow.

Tagged as: 1 Comment