Link to home
Start Free TrialLog in
Avatar of Olukayode Oluwole
Olukayode OluwoleFlag for Canada

asked on

How can i avoid repeating the same script/method in every form

I have these  4 buttons across on all my c# windows application forms
(Save,Update,Delete and Exit)  see  buttons  below

User generated image
On 1 on the forms  I have done the following which works as desired.

1. on form_load  I  call a library  that accesses  the database to determine whether a button should be visible or not
see the form_load  call to the library below:

1. In my Form-Load Event

 FormPermissionsProcessor processor = new FormPermissionsProcessor();
 var result = processor.GetFormExecStatus();
 SetButtons();


2. In my Library the status each button is determined after reading this from a database

  public class FormPermissionsProcessor
    {
       
       
        public Tuple<string, string, string,string> GetFormExecStatus()
        {
            PermissionsModel model = new PermissionsModel();

            GlobalConfig.Connection.GetFormPermissions();       // This line goes into the database to fetch the variables below
            string libregstatus = LoginDetails.staticformexecute;
            string libreglevel =  LoginDetails.staticaddbutton;
            string liblicensetype = LoginDetails.staticupdatebutton;
            string libdel = LoginDetails.staticdeletebutton;

            return new Tuple<string, string, string,string>(libregstatus, libreglevel, liblicensetype,libdel);
        }
       
    }

Open in new window


3. Method in my form that processes the returned values

 private void SetButtons()
        {
            saveButton.Visible = false;
            updateButton.Visible = false;
            deleteButton.Visible = false;
            if (LoginDetails.staticaddbutton == "Y")
            {
                saveButton.Visible = true;
            }
            if (LoginDetails.staticupdatebutton == "Y")
            {
                updateButton.Visible = true;
            }
            if (LoginDetails.staticdeletebutton == "Y")
            {
                deleteButton.Visible = true;
            }
        }

Open in new window


Currently  this process works for 1 form but i don't want to be repeating
the method in 3 above on  every form

How can I achieve this particularly since the 4 buttons (Save,Update,Delete and Exit) are local to each form

Thanks

Olukay
Avatar of kaufmed
kaufmed
Flag of United States of America image

You could create a custom user control to house the buttons. Within this control, you could expose custom events to respond to the click events.

For example:

User Control
using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class ButtonGroup : UserControl
    {
        public event EventHandler SaveButtonClick;
        public event EventHandler UpdateButtonClick;
        public event EventHandler DeleteButtonClick;
        public event EventHandler ExitButtonClick;

        public ButtonGroup()
        {
            InitializeComponent();
        }

        public void SetButtons()
        {
            this.btnSave.Visible = (LoginDetails.staticaddbutton == "Y");
            this.btnUpdate.Visible = (LoginDetails.staticupdatebutton == "Y");
            this.btnDelete.Visible = (LoginDetails.staticdeletebutton == "Y");
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            this.SaveButtonClick?.Invoke(sender, e);
        }

        private void BtnUpdate_Click(object sender, EventArgs e)
        {
            this.UpdateButtonClick?.Invoke(sender, e);
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            this.DeleteButtonClick?.Invoke(sender, e);
        }

        private void BtnExit_Click(object sender, EventArgs e)
        {
            this.ExitButtonClick?.Invoke(sender, e);
        }
    }
}

Open in new window


Form
using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ButtonGroup1_SaveButtonClick(object sender, EventArgs e)
        {
            MessageBox.Show("Save");
        }

        private void ButtonGroup1_UpdateButtonClick(object sender, EventArgs e)
        {
            MessageBox.Show("Update");

        }

        private void ButtonGroup1_DeleteButtonClick(object sender, EventArgs e)
        {
            MessageBox.Show("Delete");
        }

        private void ButtonGroup1_ExitButtonClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FormPermissionsProcessor processor = new FormPermissionsProcessor();

            var result = processor.GetFormExecStatus();

            this.buttonGroup1.SetButtons();
        }
    }
}

Open in new window


In the above, the form adds handlers to the "SaveButtonClick", "UpdateButtonClick", "DeleteButtonClick", and "ExitButtonClick" events. In this way, you can allow each form to respond differently when a particular button is clicked.

The user control itself deals with making the call to determine button visibility. That is handled by making the SetButtons method public--so the form itself can call it. It won't be visible to anyone except the form to which the user control is added.

Take note that the question marks next to each Invoke call are important. These (implicitly) check for null events. If you don't check for null, and you don't add a handler to a particular event, then Invoke will throw an exception when it is called.

I won't harp on your use of static methods/properties too much other than to say that you should work toward not relying on static members as much. Try to use instance members as much as possible.

User generated image
Avatar of Olukayode Oluwole

ASKER

Please confirm the following:

What you have suggested means that the User Control Script will be defined Once for the whole application

and the Form script will be on every form in the application.

Is that  correct  ?

If so The script that I am trying NOT to replicate will be much shorted than this suggestion

Is it not better in that case to stay with my old script  as i was looking NOT to keep repeating the code in my original post

in every form.

What do you think

Olukay
Well, it's defined once as in it's only one class, but, just like a button or a label or a texbox, you can drag as many of them onto your form as you like. The user control shows up as a control in the toolbox:

User generated image
An alternative may be that you create a base form that contains the common controls, methods, and events. Then each form was created by inheriting the base form. In case any form requires an additional process for any particular event or method, then you can overwrite it.
kaufmed,

Just to restate that we started from my NOT wanting to repeat the method below on every form

private void SetButtons()
        {
            saveButton.Visible = false;
            updateButton.Visible = false;
            deleteButton.Visible = false;
            if (LoginDetails.staticaddbutton == "Y")
            {
                saveButton.Visible = true;
            }
            if (LoginDetails.staticupdatebutton == "Y")
            {
                updateButton.Visible = true;
            }
            if (LoginDetails.staticdeletebutton == "Y")
            {
                deleteButton.Visible = true;
            }
        }

Will your advise actually achieve this  ??  

I can see you seam to have implemented a small project on this .

Can you send it to me so i can carefully review  before implementing

Thanks


Olukay
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks