Is it possible to create individual events for the instances of a form in C#?

Asked

Viewed 59 times

1

Suppose I have a customer registration form:

        var frmCadCli1 = new frmCadastroCliente();

And I just called that form:

        frmCadCli1.Show();

When I call this form, immediately before it is shown the event Form_Load is triggered.

I happen to want to execute one Form_Load different for each instance of frmCadastroCliente, for example:

      private void btnConsulta_Click(object sender, EventArgs e)
      {
        var frmCadCli2 = new frmCadastroCliente();
      }

Corresponding form load:

        private void Form1_Load(object sender, EventArgs e)
        {
          label1.Text = "Cadastro de Clientes";

        }

Afterward:

      private void btnAltera_Click(object sender, EventArgs e)
      {
        var frmCadCli3 = new frmCadastroCliente();
      }

Corresponding form load:

        private void Form1_Load(object sender, EventArgs e)
        {
          label1.Text = "Alteração de Cadastro";

        }

The reason I’d like to execute a Form_Loaddifferent for every instance is that I would have different instances with different purposes using the same design.

This way I could, for example, use the said form as a customer registration screen, change of registration, or even as a supplier registration, just changing the properties of the form on Form_Load

  • 2

    Why not pass a parameter in the constructor and validate it? Then you use only one Form_Load() calling several different methods.

  • You say the same form load code running each time you open a new instance, right?

  • @Ricardo is actually exact the opposite, a different form load for each instance.

1 answer

2

You have to pass as parameter even. Until because you will need to save the correct registration.

    public Form(string Tipo)
    {
        InitializeComponent();
    }

And passes on the call what you want:

  private void btnConsulta_Click(object sender, EventArgs e)
  {
    var frmCadCli2 = new frmCadastroCliente("Clientes");
  }

 private void btnAltera_Click(object sender, EventArgs e)
  {
    var frmCadCli3 = new frmCadastroCliente("Fornecedores");
  }
  • I did what you said and nothing happened, besides, I did not understand very well the difference made when passing a string as parameter in creating the form.

  • How are you doing? The idea is that you do whatever you want for the other form and there you fit in the best way. I put a text but it can be anything you want, I thought of the text because of your example. To complement, your Load would look like this: public Form(string Type) { labal1.text = Type, Initializecomponent(); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.