Tuesday, May 10, 2022

c# - How to make DOWN button (in group of buttons)

The goal: Only one button from group can be down.
Every button link through Click event to this method:
private void downclick( object sender, EventArgs e ) {
  Button b = (Button)sender;

  /* if is down -> do nothing */
  if ( b.BackColor == Color.IndianRed ) return;

  /* set as down */
  b.BackColor = Color.IndianRed;

  /* deselect others */
  b.Parent.Controls
    .Cast<Control>()
    .Where( x => x is Button )
    .Cast<Button>()
    .Where( x => x != b )
    .ToList()
    .ForEach( x => x.BackColor = Color.WhiteSmoke );
}
So - pushed button = Color.IndianRed. If you want to know which button is down pushed:
  /* get down button */
  Button b = groupBox1.Controls
    .Cast<Control>()
    .Where( x => x is Button )
    .Cast<Button>()
    .Where( x => x.BackColor == Color.IndianRed )
    .ToList()
    .FirstOrDefault();
        
  MessageBox.Show( b.Text );
}

No comments:

Post a Comment