Resolved Problem programming buttons

MichielJN

New member
Joined
Apr 9, 2022
Messages
2
Programming Experience
Beginner
C#:
public void BerekenTafelTegels()
{
    if (Program.Tafel2.Count == 0)
    {

    }
    else if (Program.Tafel2.Count > 0)
    {
        int index = 0;
        foreach (List<Tegel> tafelTegels in Program.Tafel2)
        {
            if (tafelTegels.Count > 0)
            {
                foreach (Tegel tegel in tafelTegels)
                {
                    if (t1.Visible == false)
                    {

                        t1.Text = $"{tafelTegels[index].Nummer}";
                        t1.AccessibleDescription = $"{tafelTegels[index].Duplicaat}";
                        if (index == 0 || index == tafelTegels.Count - 1)
                        {
                            t1.Enabled = true;
                        }
                        t1.Visible = true;
                        if (tafelTegels[index].Kleur == "Zwart")
                        {
                            t1.ForeColor = System.Drawing.Color.Black;
                        }
                        if (tafelTegels[index].Kleur == "Zilver")
                        {
                            t1.ForeColor = System.Drawing.Color.Silver;
                        }
                        if (tafelTegels[index].Kleur == "Rood")
                        {
                            t1.ForeColor = System.Drawing.Color.Red;
                        }
                        if (tafelTegels[index].Kleur == "Blauw")
                        {
                            t1.ForeColor = System.Drawing.Color.Blue;
                        }

                    }

This is a piece of code to decide whether to show a button or not. Every time I make a small change I have to change it for 104 buttons.
so I was wondering if it would be possible to make one small piece of code that can do this for all these particular buttons (there are more buttons on the screen).
 
Last edited by a moderator:
If the code is exactly the same for every Button then you just write a method and pass the Button in via a parameter, e.g. instead of this:
C#:
private void DisplayButton1Text()
{
    MessageBox.Show(button1.Text);
}

private void DisplayButton2Text()
{
    MessageBox.Show(button2.Text);
}
you do this:
C#:
private void DisplayButtonText(Button btn)
{
    MessageBox.Show(btn.Text);
}
and then pass in the appropriate Button when you call it.
 
If the code is exactly the same for every Button then you just write a method and pass the Button in via a parameter, e.g. instead of this:
C#:
private void DisplayButton1Text()
{
    MessageBox.Show(button1.Text);
}

private void DisplayButton2Text()
{
    MessageBox.Show(button2.Text);
}
you do this:
C#:
private void DisplayButtonText(Button btn)
{
    MessageBox.Show(btn.Text);
}
and then pass in the appropriate Button when you call it.
Thanks man, you saved me a lot of time.
 

Latest posts

Back
Top Bottom