简体   繁体   中英

Set default value in custom control

I am creating custom web control(textbox) which allows only integer data type in textbox. On button submit event if there is no data in textbox, custom control should set TextBox1.Text=0, this is what i want. This is code which i wrote.

public class MasIntTextBox : TextBox
{
    private RequiredFieldValidator req;
    private RegularExpressionValidator regex;
    public string ValGrp { get; set; }
    public string IsRequired { get; set; }//give true/yes or false/no values only

    protected override void OnInit(EventArgs e)
    {
        //this.CssClass = "inp-form";
        if (IsRequired == "true" || IsRequired == "yes")
        {
            req = new RequiredFieldValidator();
            req.ControlToValidate = this.ID;
            req.ErrorMessage = "Enter Numeric Value";
            req.Display = ValidatorDisplay.Dynamic;
            if (!string.IsNullOrEmpty(ValGrp))
                req.ValidationGroup = ValGrp;
            Controls.Add(req);
        }
        regex = new RegularExpressionValidator();
        regex.ControlToValidate = this.ID;
        regex.ErrorMessage = "Numeric Value Only";
        regex.Display = ValidatorDisplay.Dynamic;
        regex.ValidationExpression = "^\\d+(\\.\\d+)?$";
        if (!string.IsNullOrEmpty(ValGrp))
            regex.ValidationGroup = ValGrp;
        Controls.Add(regex);
        //base.OnInit(e);
    }

    protected override void Render(HtmlTextWriter w)
    {
        base.Render(w);
        if (IsRequired == "true" || IsRequired == "yes")
            req.RenderControl(w);
        regex.RenderControl(w);
    }
}

I checked few events or methods for this but they got fired after btnA_click event. I am kind of newbie in this. Any event or method i am missing? Any suggestion accepted. Thanks in Advance...

You should try to set the default value on TextBox.LostFocus event. This event fires immediately after focus is lost from the control (TextBox).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM