Reputation: 389
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:
Change the BackColor
of the clicked button to a predefined color: Color.Cycan;
Set the checked state of the clicked button from false
to true
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:
The BackColor
of the clicked button is changing successfully to Color.Cycan;
The default BackColor
of all other buttons of the same type on the same container is being set to default successfully: Color.Gray;
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
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.
Upvotes: 3