How to call a method that is general with Activeform?

1

I have an application with many forms that have all specific methods such as Create, Modify, Save and in the main form I have a toolbar that should access these methods depending on the active form, at this moment I have it but in the application it is expected to have too many forms and to do them all this way or with a switch it would take me a lot of code:

foreach (Form form in Application.OpenForms) {

            if (form.Name == ActiveForm.Name) {

              Xformulario  objformulario=(Xformulario) form;
              objformulario.guardar();
                break;
            }

        }
    
asked by Miguel Angel Holguin Gonzalez 04.01.2019 в 16:56
source

1 answer

3

You can use interfaces.

public interface IFormulario
{
    // cambia la definición de los métodos a como los uses en tu programa
    void Crear();  
    void Modificar();
    void Guardar();

    string Name { get; }
}

Then, have your forms implement the interface:

public class Xformulario : Form, IFormulario
{
    public void Crear()
    {
        // implementación del método crear
    }

    public void Modificar()
    {
        // implementación del método Modificar
    }

    public void Guardar()
    {
        // implementación del método Guardar
    }

    // la propiedad Name ya existe en la clase Form, no es necesario implementarla

    // resto de la clase
}

And finally, use Linq to avoid the ifs / switches:

var formulario = Application.OpenForms
    // te va a devolvar solo los formularios que implementan la interfaz IFormulario
    .OfType<IFormulario>() 
    // y con esto nos traemos el formulario que concuerde con el nombre
    .FirstOrDefault(form => form.Name == ActiveForm.Name);

if (formulario != null)
{
    // ya que formulario es de tipo IFormulario, puedes mandar llamar a Guardar sin problemas
    formulario.Guardar();
}
    
answered by 04.01.2019 / 17:11
source