C# Что такое «отправитель объекта» формы? - PullRequest
0 голосов
/ 04 апреля 2020

У меня есть форма и есть кнопка и метка. У меня есть обработчик события "Click", кнопка и форма имеют одинаковый обработчик события Click. Я хочу сделать, если «отправитель» из Button print: Hello From Button и если «отправитель» из Form print: Hello World. Я знаю, что мы можем сделать это, если еще, но как называется форма? Когда я беру имя формы из свойств, оно генерирует ошибку и говорит, что это Type.

public partial class simpleEventExample : Form
{        

    public simpleEventExample()
    {
        InitializeComponent();

    }

    private void firstButton_Click(object sender, EventArgs e )
    {
        if (sender == firstButton )
        {
            displayLabel.Text = "Hello From Button";

        }
        if (sender == simpleEventExample )  ***//(Error says it is type)***
        {
            displayLabel.Text = "Hello World";
        }

    }

}

Посмотрите на имя картинки просто enter image description here

Ответы [ 3 ]

2 голосов
/ 04 апреля 2020

вы хотите проверить против this ... не simpleEventExample

public partial class simpleEventExample : Form
{        

    public simpleEventExample()
    {
        InitializeComponent();

    }

    private void firstButton_Click(object sender, EventArgs e )
    {
        if (sender == firstButton )
        {
            displayLabel.Text = "Hello From Button";

        }
        if (sender == this )  // this means the object whos member the current function is... in other words.. your form ... 
        {
            displayLabel.Text = "Hello World";
        }
        else if ((sender as simpleEventExample)?.Name == "simpleEventExample")  // if you REALLY need to check the name...  
        {
            displayLabel.Text = "Hello World";
        }


    }

}
1 голос
/ 04 апреля 2020

Решением вашей ошибки было бы сделать это:

if (sender == this)

Или это:

if (sender is simpleEventExample)
//if (sender is Form) // This is also okay.

... и все это может стать:

if (sender is Button )
{
    displayLabel.Text = "Hello From Button";
}

if (sender is simpleEventExample )
{
    displayLabel.Text = "Hello World";
}

Но я бы посоветовал вам не использовать обработчики событий как общее правило, особенно между различными элементами управления.

0 голосов
/ 04 апреля 2020

Делай как ниже.

public partial class simpleEventExample : Form
{        

    public simpleEventExample()
    {
        InitializeComponent();

    }

    private void firstButton_Click(object sender, EventArgs e )
    {
        if (sender is Button)
        {
            displayLabel.Text = "Hello From Button";
        }
        else
        {
            displayLabel.Text = "Hello World";
        }

    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...