0

I tried something like:

RadioButton[] diff = new RadioButton[10];

for (int i = 0; i < 10; ++i)
{
    diff[i] = (RadioButton)Control("rad_D" + i.ToString());
}

Clearly does not work. But what was the correct way?

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Shibli
  • 5,879
  • 13
  • 62
  • 126
  • 1
    Not clear what you are trying to do. Are you trying to find all the RadioButtons with names of "rad_D*x*"? – Matt Burland Mar 17 '12 at 16:43
  • @MattBurland: Something like that. I have several radiobuttons named "rad_D0", "rad_D1"... Then I wanted to add them to an array of radiobuttons. – Shibli Mar 17 '12 at 16:57

2 Answers2

0

Edit: Ok, so you are looking for already existing RadioButtons, in that case, use FindName. Something like this:

RadioButton[] diff = new RadioButton[10];

for (int i = 0; i < 10; ++i)
{
    diff[i] = someparentControl.FindName("rad_D" + i.ToString()) as RadioButton;
}

You need a parent control, which can just be the window itself as it will search recursively for a matching name.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • I dont want to create radiobuttons. They are created anyway. I just want to equate array of radiobuttons to already existing radiobuttons. – Shibli Mar 17 '12 at 17:05
0

Try this, if the radio buttons are direct children of a Panel such as a Grid, StackPanel etc then you can do this:

var buttons = grid.Children.OfType<RadioButton>().
    Where(rb => rb.Name.StartsWith("rad_D").ToList();

to obtain a List, or if you really want an array

var buttons = grid.Children.OfType<RadioButton>().
    Where(rb => rb.Name.StartsWith("rad_D").ToArray();

And you can use this article Find all controls in WPF Window by type which has several methods for finding all controls of a specific type.

Community
  • 1
  • 1
Phil
  • 42,255
  • 9
  • 100
  • 100