Russell Chidhakwa
Russell Chidhakwa

Reputation: 389

How to select one Button at a time in a Button Group in .NET Winforms

I have made a custom button control and want it to behave like RadioButtons in a group. The button will be placed in a group or collection of its type on the same container or panel (button dragged_dropped onto the container). When i click any of these buttons, i need the following to happen:

  1. Change the BackColor of the clicked button to a predefined color: Color.Cycan;

  2. Set the checked state of the clicked button from false to true

  3. Ensure that all other buttons of the same type on the same panel/container are set to their default settings which are: BackColor = Color.Gray; checked = false;

I have tried the below code but i am obtaining this result:

  1. The BackColor of the clicked button is changing successfully to Color.Cycan;

  2. The default BackColor of all other buttons of the same type on the same container is being set to default successfully: Color.Gray;

  3. But the checked state of the clicked button is not changing to true. It remains false.

I have attached the code i have tried, below:

What could be the issue or where am i missing the point?

This is a Winform / Windows Forms button control and i am programming in C#.

I do not want to use a radio button for this because i have custom designed MyButton.

Thank you.

THIS IS THE CODE I HAVE TRIED:

// Calling 'ClickedButton();' on click event.

private bool checked = false;
private void ClickedButton()
{

do(

BackColor = Color.Cycan;
checked = true;

if(Parent == null)
break;

foreach(MyButton button in Parent.Controls.OfType<MyButton>())
{

if(button == this) { continue }

else{

BackColor = Color.Gray;
checked = false;
}
}

)
while(false)
}

Upvotes: 1

Views: 1189

Answers (1)

Hotkey
Hotkey

Reputation: 450

How about use this method?

private bool isSelected = false;

private Color activeColor = Color.FromArgb(117, 117, 117);
private Color defaultColor = Color.FromArgb(66, 66, 66);

private void ClickedButton()
{
    foreach (Control parentControl in Parent.Controls)
    {
        if (parentControl is MyButton parentButton)
        {
            parentButton.isSelected = false;
            parentButton.BackColor = parentButton.isSelected ? parentButton.activeColor : parentButton.defaultColor;
        }
    }

    this.isSelected = true;
    this.BackColor = isSelected ? activeColor : defaultColor;
}

It works like this.

buttonTest

Upvotes: 3

Related Questions