Passing values betwwen Windows Forms in Realtime - Using Delegates and Events

Hi all, in this post I'll explain how to use delegates to pass value to another form.
To demonstrate this I'll use windows forms.

Task:
1. There is a Windows form called Tool. And there is another Windows form called Register.
2. We need to get the name of the user from the Register form to the Tool form.

I have created a Windows form project and named it as BaseNumbers. You can use any number as you like.
Then I have designed the 2 forms as bellow.



To make the things work we have to use delegates and events.

Register Form

namespace BaseNumbers
{
    public delegate void RegisterUser(string name);

    public partial class Register : Form
    {
        public event RegisterUser registerUser;

        public Register()
        {
            InitializeComponent();
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text != "")
            {
                if (registerUser != null)
                {
                    registerUser(txtUsername.Text);
                }
            }
            else
            {
                lblMessage.Visible = true;
            }
        }
    }
}

Let me explain the Register form.
I have add a delegate called RegisterUser.
Then inside the class I have created an event called registerUser using that delegate.
Within the Register button click I'm adding the Username text box value after doing some null and empty validations.

Tool Form

namespace BaseNumbers
{
    public partial class Tool : Form
    {
        public Tool()
        {
            InitializeComponent();
        }

        private void btnPlayGame_Click(object sender, EventArgs e)
        {
            Register register = new Register();
            register.registerUser += register_registerUser;
            register.ShowDialog();
        }

        void register_registerUser(string name)
        {
           var _username = name;
        }
    }
}

Now in the Tool form when clicking the PlayGame button, I'm creating a new Register form object.
Then using that register form object I'm overloading (using += operator) the registerUser event in the Register form.
Within the event's overload function I'm getting the value passed by delegate to a variable.

Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#