Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access events of View from Controller

My question is regarding implementing MVC pattern in winforms

I learned that the controller object is responsible for handling the events raised in the view. Can any one please tell me how can the controller reacts to the text input or button press event in the view? I mean how can the controller know that some event happened without it being handled in the view as these controls(textbox,button) are private to view.

like image 558
logeeks Avatar asked Nov 14 '11 14:11

logeeks


People also ask

What is event Handler MVC?

The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler. If it has, the event handler is executed.

What is EventArgs C#?

The EventArgs class is the base type for all event data classes. EventArgs is also the class you use when an event doesn't have any data associated with it.

Which is the best place to subscribe event handler to an event?

To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.

What happens if an event occurs and there is no event handler to respond to the event?

TF: if an event occurs and there is not event handler to respond to that event, the event ins ignored.


2 Answers

The idea is that the view catches the event and then call on an appropriate function in the controller. In Windows Forms that means that you'll attach an event handler for e.g. "button_click", which then call on controller.doFoo().

You might be interessted in reading GUI Architectures at Martin Fowlers site.

like image 158
Håkon K. Olafsen Avatar answered Sep 22 '22 19:09

Håkon K. Olafsen


 public partial class Form1 : Form
    {
        private Controller controller;
        public Form1()
        {
            InitializeComponent();
        }
        //Dependency Injection
        public Form1(Controller controller):this()
        {
            //add more defensive logic to check whether you have valid controller instance
            this.controller = controller;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (controller != null)
                controller.MethodA();
        }
    }
    //This will be another class/ controller for your view.
    public class Controller
    {
        public void MethodA() { }
    }
like image 38
s_nair Avatar answered Sep 25 '22 19:09

s_nair