SkyterX
SkyterX

Reputation: 123

How to change currently checked RadioButton of RadioButton group in C# properly

I have a GroupBox with a bunch of RadioButtons. When they have focus I can use keys up/down to iterate through them.

But when I manually change checked RadioButton and press up/down, iteration proceeds from the point it was before changing checked RadioButton. The questions are:

Answer: To handle the event of TAB, ESC, RETURN or ARROW buttons KeyDown you need to override IsInputKey method of the control. Or override ProcessCmdKey instead of KeyDown.

Answer: Besides setting radioButton.Checked = true. You need to set focus on it - radioButton.Focus().

Example: I have group of 6 RadioButtons (0-5).

Upvotes: 2

Views: 5912

Answers (3)

Ken Kin
Ken Kin

Reputation: 4683

  1. What event corresponds to up/down key click on RadioButton?

    There is no event corresponds to the individual RadioButtons that you can press a key without releasing but still process the key commands. However, you can override the ProcessCmdKey method which your form inherited it from Form:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        Console.WriteLine("123"); 
        return false; 
    } 
    
  2. How to access internal indexer of RadioButton group?

    TabIndex property. There is no internal index of individual RadioButtons. But since you put them on a GroupBox which is a Control, and have a inherited property named Controls is a collection of it's child controls.

The problem presents by the example, appears the problem of TabIndex.

Control is the base class of most visual components of WinForm applications. It has a parent/child hierarchy, all the RadioButtons you put on the GroupBox have the same parent, and the GroupBox itself owns these RadioButtons, and have the property Controls which you can access them by index.

Upvotes: 2

Anton Semenov
Anton Semenov

Reputation: 6347

ok, when the user presses up/down button he/she just moves the focus across radio buttons. so you need to just call method Focus() of the button you just set checked property to true

Upvotes: 1

Nicolas Tyler
Nicolas Tyler

Reputation: 10552

You could get the selected radiobutton like this:

RadioButton checkedButton = Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked);

And you could add the checkChanged event to all the radiobuttons.

This will get the index of the radio button thats selected:

int index = groupBox1.Controls.IndexOf(groupBox1.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked));

This will select a specific index:

groupBox1.Controls.OfType<RadioButton>().ElementAtOrDefault(index).Select();

Upvotes: 0

Related Questions