Search code examples
c#winformsrepeat

Do we have to repeat our code in a WinForms application?


So I'm trying to switch from C# console to form, but I always read that never repeat our code etc.

My first project would be a calculator, and I found a site just to take a look how it looks like in win form, but in this code there are a lot of repeating. Is this normal in form, in let's say a calculator?

Here is the link that I am talking about.


Solution

  • That is a lot of repetition, to improve it add one click event handler for all of the buttons, eg:

    btn1.Click += btnClick;
    btn2.Click += btnClick;
    

    Then cast the sender to a Button to get which one was clicked, a rough example:

    private void btnClick(object sender, EventArgs e)
    {
        var btnName = ((Button)sender).Name;
        var btnValue = btnName.Replace("btn",string.Empty);
    
        if (textBox1.Text == "0" && textBox1.Text != null)  
        {  
            textBox1.Text = btnValue;  
        }  
        else  
        {  
            textBox1.Text = textBox1.Text + btnValue;  
        }  
    }
    

    Don't forget to unhook the event subscriptions in the form unload event:

    btn1.Click -= btnClick;
    btn2.Click -= btnClick;