C# Windows Forms App: Separate GUI from Business Logic

Viewed 8895

I would like some advice on how to separate the UI and business logic in a simple C# Windows Forms Application.

Let's take this example:

The UI consists of a simple textbox and a button. The user enters a number between 0 and 9 and clicks the button. The program should add 10 to the number and update the text box with that value.

enter image description here

The business logic part should have no idea of the UI. How can this be accomplished?

Here's the empty Process class (Business Logic):

namespace addTen
{
    class Process
    {
        public int AddTen(int num)
        {
            return num + 10;
        }
    }
}

The requirement is:

  1. When the user clicks the button, somehow, the Process::AddTen gets invoked.
  2. The Textbox must be updated with the return value of Process::AddTen.

I just don't know how to connect these two.

4 Answers

To separate the logic completely you can declare a base class that can contain the button and manage handlers. Your specific process can inherit the base class, and the logic can be set. Finally the form can declares an instance of the class and pass in the button.

It looks something like this:

class BaseProcessor
{

    System.Windows.Forms.Button myButton;
    public System.Windows.Forms.Button MyButton
    {
        get
        {
            return myButton;
        }
        set
        {
            myButton = value;
            myButton.Click += new System.EventHandler(this.MyButton_Click);
       }
    }

    public BaseProcessor()
    {
    }

    public virtual void MyButton_Click(object sender, EventArgs e)
    {
    }

Then declare the process:

class MyProcess : BaseProcessor
{

    public override void MyButton_Click(object sender, EventArgs e)
    {
        MessageBox.Show("This is my process");
    }
}

Then inside the form, declare an instance of the process and attach the button:

public partial class Form1 : Form
{

    MyProcess myProcess = null;

    public Form1()
    {
        InitializeComponent();

        myProcess = new MyProcess
        {
            MyButton = button1
        };
    }

}

Using this method, there is no business logic code in the form. The parent class is useful because events like clicking buttons are pretty common so its easier to declare them centrally, in my opinion.

Related