0

I want to call a validation function in all load event form but i want to avoid to put the code in load event (this proyect has 50+ forms). Is there a way to do this?

private void frmPrincipal_Load(object sender, EventArgs e) 
{    
    //i want to avoid this code in all forms
    if ( validation() == false )
        System.Windows.Forms.Application.Exit()    
}
  • Yes, you right, I want to execute a validation function when the load event starts but i dont want to write this code block in all forms (it makes dity code) , so i want to know if there is a way to avoid it in load event. – Cristhian Cobeñas Huamani Jul 03 '20 at 19:46

2 Answers2

2

You can create a specialized form named ValidatedForm for example.

Add to your VS project a new empty class and add all you need to it :

using System;
using System.Windows.Forms;

namespace SomeNamespace
{

  public class ValidatedForm : Form
  {

    public ValidatedForm()
      : base()
    {
    }

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      if ( !validation() )
        Application.Exit();
    }

  }

}

Next change the ancestor Form by ValidatedForm for all the forms you want :

public partial class SomeForm : ValidatedForm

Now all of them inherit the new behavior.

But be carefull that at design time the validation method can close VS, hence you may need to check in it if you're in design time.

How to check if i'm in run-time or design time?

0

So you have some code that needs to be executed at the Load of any of your forms. You can create a static method in a global class (I usually use a static class):

public static class Engine
{
    public static void anyForm_Load(object sender, EventArgs e)
    {
        if (validation() == false)
            System.Windows.Forms.Application.Exit();
    }
}

And then, in each of your forms, in the constructor, you add this line and it knows that when that form loads, it will execute whatever is in that method:

    public Form1()
    {
        InitializeComponent();
        this.Load += Engine.anyForm_Load;
    }

Hope this helps :)

Nicholas
  • 87
  • 9