Answer the question
In order to leave comments, you need to log in
How to add custom event on button click?
Good afternoon, I read a lesson on adding arguments to an event. But in the example there was an event call when the program was executed.
//addAgent.OnAddAgent += AddAgent2;
public class AddAgentEventArgs : EventArgs
{
public string AddAgentInfo { get; set; }
}
public delegate void AddAgentE(object sender, AddAgentEventArgs e);
public class AddAgent
{
public event AddAgentE OnAddAgent;
public void AddAgentMain(string test)
{
if (OnAddAgent != null)
{
// Создаём объект аргумента события и помещаем в него текст письма
var e = new AddAgentEventArgs { AddAgentInfo = test };
OnAddAgent(this, e);
}
}
}
AddAgent addAgent = new AddAgent();
private void newAgent()
{
Button ButtonAddAgent = new Button();
ButtonAddAgent.Text = "Добавить агента";
ButtonAddAgent.AutoSize = true;
ButtonAddAgent.Location = new System.Drawing.Point(290, 200);
//addAgent.OnAddAgent += AddAgent2;
addAgent.AddAgentMain(TextBoxSurName.Text);
ButtonAddAgent.Click += new System.EventHandler(AddAgent1);
splitContainer1.Panel2.Controls.Add(ButtonAddAgent);
}
private void AddAgent1 (object sender, EventArgs e)
{
addAgent.OnAddAgent += AddAgent2;
MessageBox.Show("test1");
}
private void AddAgent2(object sender, AddAgentEventArgs e)
{
Console.WriteLine("test2");
MessageBox.Show(e.AddAgentInfo);
}
Answer the question
In order to leave comments, you need to log in
In AddAgent1 you didn't call AddAgent2, you only subscribed to the OnAddAgent event.
What's going on with you:
addAgent.AddAgentMain(TextBoxSurName.Text);
ButtonAddAgent.Click += new System.EventHandler(AddAgent1);
private void newAgent()
{
Button ButtonAddAgent = new Button();
ButtonAddAgent.Text = "Добавить агента";
ButtonAddAgent.AutoSize = true;
ButtonAddAgent.Location = new System.Drawing.Point(290, 200);
ButtonAddAgent.Click += new System.EventHandler(AddAgent1);
addAgent.OnAddAgent += AddAgent2;
splitContainer1.Panel2.Controls.Add(ButtonAddAgent);
}
private void AddAgent1 (object sender, EventArgs e)
{
MessageBox.Show("Before firing OnAddAgent event");
addAgent.AddAgentMain(TextBoxSurName.Text);
}
private void AddAgent2(object sender, AddAgentEventArgs e)
{
Console.WriteLine("Inside OnAddAgent event handler");
MessageBox.Show(e.AddAgentInfo);
}
public void AddAgentMain(string test)
{
var handler = OnAddAgent;
if (handler != null)
{
// Создаём объект аргумента события и помещаем в него текст письма
var e = new AddAgentEventArgs { AddAgentInfo = test };
handler(this, e);
}
}
public void AddAgentMain(string test)
{
// Создаём объект аргумента события и помещаем в него текст письма
var e = new AddAgentEventArgs { AddAgentInfo = test };
OnAddAgent?.Invoke(this, e);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question