Question

I have some validation code in my WebForm page. When a user clicks on a button and does a postback.

Page_Load event gets processed then the Button1_Click event gets processed.

I can't figure out a way to stop the Button1_Click event from processing if the validation fails on Page_Load.

Is a trick to do this?

Thanks

Was it helpful?

Solution

4 variations shown below.

 public partial class _Default : System.Web.UI.Page
    {
        private bool MyPageIsValid { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Page.IsPostBack)
            {
                bool valid = false; /* some routine here */
                MyPageIsValid = valid;
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.MyPageIsValid)
            {
                this.TextBox1.Text = DateTime.Now.ToLongTimeString();
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {

            if (!this.MyPageIsValid) {return;}

            this.TextBox1.Text = DateTime.Now.ToLongTimeString();

        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid)
            {
                this.TextBox1.Text = DateTime.Now.ToLongTimeString();
            }
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid) {return;}

            this.TextBox1.Text = DateTime.Now.ToLongTimeString();

        }
    }

OTHER TIPS

I think it should be better to check validation conditions exactly in the Button1_Click method like this:

if (!this.IsValid()) { return; }

Also if you still want to check that conditions in Page_Load method just add simple 'bool isValid' flag to your page's class and then check it in Button1_Click:

if (!this.isValid) { return; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top