⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Passing Parameters Between Forms in C#

Often there is a need to pass certain parameters between forms in one application, for example, values of certain variables, or run a procedure or function in another form. Here I will tell you about two methods of solving this problem. The described methods I use myself, so I'm publishing them. The first method is simpler, the second is more complex but more universal and has more possibilities.



Method #1
Passing parameters using a connection between forms. (I named it this way myself - maybe there is a scientific name).

Here everything is quite simple. Let's assume that from the main form we launch another form, from which we later want to get some data, or allow the newly created form to perform some actions with the first one. To do this, we can do it like this:

In the main form (parent) we launch a new form like this:

FormNew frm = new FormNew();
frm.Owner = this; //Передаём вновь созданной форме её владельца.
frm.Show(); 



After such an action in the new form we can access the elements of the parent form, like this:

FormMain frm = (FormMain)this.Owner;
frm.MyFunc(); //MyFunc - это ваша функция основной формы.



That's it, the first method. You can also pass variables in this way, but in the case when you need to connect not two forms but several, or it's hard to track the relationship between forms, it's easier to use the second method.

Method #2
By events (Delegates)

1. We create a class in the main namespace (this is in the file program.cs):

public static class CallBackMy
    {
        public delegate void callbackEvent(string what);
        public static callbackEvent callbackEventHandler;
    }



2. Then we add a receiver form (there can be several - which is very convenient):

public FormMy()
{
// Добавляем обработчик события - который запустит функцию Reload
CallBackMy.callbackEventHandler = new CallBackMy.callbackEvent(this.Reload);
InitializeComponent();
}

void Reload(string param)
{
//Здесь чего нибудь делаем.
//Это непосредственно то что выполнится по событию.
}



3. In the source form we generate an event (where we need it).

CallBackMy.callbackEventHandler("Передаваемые данные.");



By this method you can exchange data between forms and run procedures and functions in other forms, without any connection between the forms themselves. At the same time, you can force many similar forms to perform the same operations, which is convenient.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.