Skip to content

Instantly share code, notes, and snippets.

@vertigra
Last active February 9, 2017 04:39
Show Gist options
  • Save vertigra/15f0c69a9dc5b78e38f6f72a8c41544a to your computer and use it in GitHub Desktop.
Save vertigra/15f0c69a9dc5b78e38f6f72a8c41544a to your computer and use it in GitHub Desktop.
Обработка и вызов события без передачи параметров (C#)

Обработка и вызов события без передачи параметров (C#)

Дано:

  1. Форма MainForm, на которой расположены два текстбокса (TextBoxOne и TextBoxTwo) и кнопка buttonСallParentForm вызывающая ParentForm.
  2. Форма ParentForm, c кнопкой buttonCleanTextBox при нажатии на которую нужно очистить текстбоксы на первой форме.

##На ParentForm

public delegate void MethodContainer();
public event MethodContainer OnButtonOkClick;

protected virtual void OnOnButtonOkClick()
{
    OnButtonOkClick?.Invoke();
}

В событии нажатия кнопки buttonCleanTextBox

private void buttonCleanTextBox_Click(object sender, EventArgs e)
{
    OnOnButtonOkClick();
}

##На MainForm

Объявляем переменную класса:

public partial class FormMain : Form
{
    private FormParent mFormParent;
    
    ...

На кнопке вызывающей ParentForm:

private void buttonСallParentForm_Click(object sender, EventArgs e)
{
    mFormParent = new FormInputBox();
    mFormParent.OnButtonOkClick += OnButtonOkClick;
    mFormParent.Show();
}

В методе OnButtonOkClick:

private void OnButtonOkClick()
{
    textBoxOne.ResetText();
    textBoxTwo.ResetText();

    mFormInputBox.OnButtonOkClick -= OnButtonOkClick;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment