Public Custom Event on UserControl - c#

I want this:
public partial class ucTest : UserControl
{
...
SomeEvent { MessageBox.Show("Inner Call") }
}
public partial class frmTest: Form
{
...
SomeEvent += OuterEventInstance;
...
void OuterEventInstance(object sender, EventArgs e)
{ MessageBox.Show("Inner Call") }
...
}
How can I define a public event on a user control that is available (and expandable) in the form that contains an instance of this user control?

Something like this:
public partial class ucTest : UserControl
{
public event EventHandler SomeEvent;
private void OnSomeEvent()
{
EventHandler handler = SomeEvent;
if(handler != null)
handler(this, EventArgs.Empty);
}
}
public partial class frmTest: Form
{
public frmTest()
{
ucTest uc = new ucTest();
uc.SomeEvent += OuterEventInstance;
}
//...
void OuterEventInstance(object sender, EventArgs e)
{
MessageBox.Show("Inner Call")
//...
}
}

Related

C# EventHandler returns null when called

I have a two classes.In one class i am creating and raising an event as follows :
CustomerAdd Class
public class CustomerAdd
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated(this, EventArgs.Empty);
}
}
}
MyWindow Class
public class MyWindow
{
private void SaveToDisk()
{
CustomerAdd cuss = new CustomerAdd();
cuss.ListUpdated += new CustomerAdd.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails()
{
//other codes here
}
}
Now, when i call the SaveToDisk method from MyWIndow class,(as i am subscribing DisplayDetails method to the ListUpDated event) , DisplayDetails is not called. The debugger shows that ListUpdated is null. I have searched for hours and failed to come up with a solution.I followed this link but still ListUpdated is null. Any guidance/help would be highly appreciated.
It works:
using System;
namespace ConsoleApp2
{
class Program
{
public class CustomerAdd1
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated(this, EventArgs.Empty);
}
}
}
public class CustomerAdd
{
public void SaveToDisk()
{
CustomerAdd1 cuss = new CustomerAdd1();
cuss.ListUpdated += new CustomerAdd1.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails(object Sender, EventArgs e)
{
Console.WriteLine("Test");
}
}
static void Main(string[] args)
{
var c = new CustomerAdd();
c.SaveToDisk();
Console.ReadLine();
}
}
}
Try this:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
CustomerReceive cr = new CustomerReceive();
cr.SaveToDisk();
}
}
public class CustomerAdd
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated.Invoke(this, EventArgs.Empty);
}
}
}
public class CustomerReceive
{
public void SaveToDisk()
{
CustomerAdd cuss = new CustomerAdd();
cuss.ListUpdated += new CustomerAdd.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails(object Sender, EventArgs e)
{
int k = 0;
}
}
}
You need to do a good read on delegates and events because this is not working when there are more listeners

Create EventHandler and listen to Event from another class

I've created event as bellow and want to listen to it and execute method in another class when it fires
but saveEvent always comes to be null and it doesn't fire
I don't know what I've missed
here's my first class has button
internal partial class OpenSaveReportWizardForm : Form
{
public event EventHandler saveEvent;
private void saveButton_Click(object sender, EventArgs e)
{
saveEvent?.Invoke(this, e);
}
}
and here's the second class where I want to listen to saveEvent
internal class Database
{
public Database()
{
Program._wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );
}
public void HandleSaveMethod()
{
// do something
}
here's where I open the form
internal class Program
{
public static OpenSaveReportWizardForm _wizardForm;
private static void Main()
{
OpenFileCommandHandler();
}
void OpenFileCommandHandler()
{
_wizardForm = new OpenSaveReportWizardForm( );
_wizardForm.ShowDialog();
}
}
Because you disposed wizardForm, after that event is cleared.
You should write next code:
internal class Database
{
private bool _isDisposed;
private OpenSaveReportWizardForm _wizardForm;
public Database()
{
_wizardForm = new OpenSaveReportWizardForm(m_Opening,m_ConnectionProperties,m_ColumnProperties))
_wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );
}
public void HandleSaveMethod()
{
// do something
}
public void Dispose()
{
if(_isDisposed)
return;
_isDisposed = true;
_wizardForm.saveEvent -= HandleSaveMethod;
_wizardForm.Dispose();
}

Winforms MVP show mdi child form

Guys i have problem with MVP design pattern becouse am not shure how can i show child view in parent form.
My view does not have MdiParent property. Can i manually create it in view interface?
Very ugly look to every form opens in a new window!
I have two presenters:
MainPresenter (represent mainForm(parent) logic)
TaskPresenter (represent logic for save,insert,delete logic)
Two View interfaces:
IMainView
ITaskView
And two winforms:
MainForm - mainwindow(parrent mdi form)
TaskForm
Check code:
MainPresenter
public class MainPresenter
{
private readonly IMainView view;
private List<ITaskModel> tasks;
// Constructor
public MainPresenter(IMainView view)
{
this.view = view;
this.Init();
this.tasks = new List<ITaskModel>();
}
// Initialize
private void Init()
{
this.view.AddTask += AddTask;
}
// Add task
private void AddTask(object sender, EventArgs e)
{
// Show as MDI CHILD
}
}
IMainView
public interface IMainView
{
event EventHandler<EventArgs> AddTask;
}
TaskPresenter
public class TaskPresenter
{
private readonly ITaskView view;
private List<ITaskModel> tasks;
private bool isNew = true;
private int currentIndex = 0;
// Constructor
public TaskPresenter(ITaskView view)
{
this.view = view;
this.Initialize();
}
// Initialize
public void Initialize()
{
tasks = new List<ITaskModel>();
view.SaveTask += Save;
view.NewTask += New;
view.PrevTask += Previous;
view.NextTask += Next;
}
private void Save(object sender, EventArgs e)
{
}
private void New(object sender, EventArgs e)
{
}
private void Next(object sender, EventArgs e)
{
}
private void Previous(object sender, EventArgs e)
{
}
private void BlankTask()
{
}
private void LoadTask(ITaskModel task)
{
}
}
ITaskView
public interface ITaskView
{
String TaskName { get; set; }
String TaskPriority { get; set; }
DateTime? StartDate { get; set; }
DateTime? DuoDate { get; set; }
event EventHandler<EventArgs> SaveTask;
event EventHandler<EventArgs> NewTask;
event EventHandler<EventArgs> NextTask;
event EventHandler<EventArgs> PrevTask;
}
And here is MainForm
public partial class MainForm : Form, IMainView
{
MainPresenter Presenter;
// Construcor
public MainForm()
{
InitializeComponent();
}
// Events
public event EventHandler<EventArgs> AddTask;
// On load
private void MainForm_Load(object sender, EventArgs e)
{
Presenter = new MainPresenter(this);
}
// On click add task btn
private void addTaskBtn_Click(object sender, EventArgs e)
{
if(AddTask != null)
{
// When is this event triggered i want to show another child form for adding new task
AddTask(this, EventArgs.Empty);
}
}
}
So how can i show TaskView as child in MainView?
UIApplication it is Windows Forms Application but output type Class Library.
Add referance MVPFramework
MainForm
public partial class MainForm : Form , IMainView
{
[Resolve]
public IMainControl mainControl;
public MainForm()
{
InitializeComponent();
}
public bool ShowAsDialog()
{
throw new NotImplementedException();
}
private void openChildFormToolStripMenuItem_Click(object sender, EventArgs e)
{
mainControl.OnOpenChildForm();
}
}
Child Form
public partial class ChildForm : Form , IChildView
{
public ChildForm()
{
InitializeComponent();
}
public bool ShowAsDialog()
{
throw new NotImplementedException();
}
public object MDIparent
{
set
{
this.MdiParent = (Form)value;
}
}
}
CoreApplication it is class Library
IMainControl
public interface IMainControl :IControl
{
void OnOpenChildForm();
}
MainControl
public class MainControl :IMainControl
{
[Resolve]
public IApplicationController applicationController;
public void OnOpenChildForm()
{
IChildControl TransfersOnTheWayControl = applicationController.Resolve<IChildControl>();
TransfersOnTheWayControl.Run();
}
}
IChildControl
public interface IChildControl :IControl
{
void Run();
}
IMainView
public interface IMainView :IView
{
}
IChildView
public interface IChildView :IView
{
bool ShowAsDialog();`enter code here`
object MDIparent { set; }
}
IMainPresenter
public interface IMainPresenter :IPresenter
{
}
IChildPresenter
public interface IChildPresenter :IPresenter
{
bool Ask();
}
MainPresenter
public class MainPresenter :BasePresenter<IMainView>, IMainPresenter
{
}
ChildPresenter
public class ChildPresenter : BasePresenter<IChildView>, IChildPresenter
{
public bool Ask()
{
this.Init();
bool res = View.ShowAsDialog();
ApplicationController.ClearInstance<IChildView>();
return res;
}
public override void Init()
{
View.MDIparent = ApplicationController.GetMainFrom<IMainPresenter>();
base.Init();
}
}
LauncherApplication it is Console Application but output type Windows Form.
class Program
{
static void Main(string[] args)
{
IApplicationController applicationController = new ApplicationController(new ServicesContainerAdapter());
applicationController
//RegisterView
.RegisterView<IMainView, MainForm>()
.RegisterView<IChildView, ChildForm>()
//RegisterPresenter
.RegisterPresenter<IMainPresenter, MainPresenter>()
.RegisterPresenter<IChildPresenter, ChildPresenter>()
//RegisterController
.RegisterController<IMainControl, MainControl>()
.RegisterController<IChildControl, ChildControl>();
IMainPresenter mainPresenter = applicationController.Resolve<IMainPresenter>();
mainPresenter.Init();
Application.Run((Form)mainPresenter.FormObject);
}
}

WinForm events in another class .NET2 Simplify delegate

Any way to make this working code simpler ie the delegate { }?
public partial class Form1 : Form
{
private CodeDevice codeDevice;
public Form1()
{
InitializeComponent();
codeDevice = new CodeDevice();
//subscribe to CodeDevice.ConnectionSuccessEvent and call Form1.SetupDeviceForConnectionSuccessSate when it fires
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
}
private void SetupDeviceForConnectionSuccessState(object sender, EventArgs args)
{
MessageBox.Show("It worked");
}
private void button1_Click(object sender, EventArgs e)
{
codeDevice.test();
}
}
public class CodeDevice
{
public event EventHandler ConnectionSuccessEvent = delegate { };
public void ConnectionSuccess()
{
ConnectionSuccessEvent(this, new EventArgs());
}
public void test()
{
System.Threading.Thread.Sleep(1000);
ConnectionSuccess();
}
}
WinForm event subscription to another class
How to subscribe to other class' events in c#?
If don't think you could simplyfy:
public event EventHandler ConnectionSuccessEvent = delegate { }
even in c#3 + you could only do
public event EventHandler ConnectionSuccessEvent = () => { }
However you could simplify
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
to
codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;

Winforms user controls custom events

Is there a way to give a User Control custom events, and invoke the event on a event within the user control. (I'm not sure if invoke is the correct term)
public partial class Sample: UserControl
{
public Sample()
{
InitializeComponent();
}
private void TextBox_Validated(object sender, EventArgs e)
{
// invoke UserControl event here
}
}
And the MainForm:
public partial class MainForm : Form
{
private Sample sampleUserControl = new Sample();
public MainForm()
{
this.InitializeComponent();
sampleUserControl.Click += new EventHandler(this.CustomEvent_Handler);
}
private void CustomEvent_Handler(object sender, EventArgs e)
{
// do stuff
}
}
Aside from the example that Steve posted, there is also syntax available which can simply pass the event through. It is similar to creating a property:
class MyUserControl : UserControl
{
public event EventHandler TextBoxValidated
{
add { textBox1.Validated += value; }
remove { textBox1.Validated -= value; }
}
}
I believe what you want is something like this:
public partial class Sample: UserControl
{
public event EventHandler TextboxValidated;
public Sample()
{
InitializeComponent();
}
private void TextBox_Validated(object sender, EventArgs e)
{
// invoke UserControl event here
if (this.TextboxValidated != null) this.TextboxValidated(sender, e);
}
}
And then on your form:
public partial class MainForm : Form
{
private Sample sampleUserControl = new Sample();
public MainForm()
{
this.InitializeComponent();
sampleUserControl.TextboxValidated += new EventHandler(this.CustomEvent_Handler);
}
private void CustomEvent_Handler(object sender, EventArgs e)
{
// do stuff
}
}

Categories