Reputation: 514
How to get the index of the selected Radiobutton control that is located inside a stackpanel (parent container) than border than radio button via c#?
here is what i am got after searching and trying
for (int i = 0; i < this.selective.Children.Count; i++)
{
if (this.selective.Children[i].GetType().Name == "RadioButton")
{
RadioButton radio = (RadioButton)this.selective.Children[i];
if ((bool)radio.IsChecked)
{
//get checked indes name
}
}
}
but here i am having radio button inside border so how to achieve the same
here is my xaml
<StackPanel Visibility="Collapsed" x:Name="selective" HorizontalAlignment="Left" VerticalAlignment="Top" Width="462" >
<Border Margin="20,0,20,0" Grid.Row="2" BorderThickness="2" BorderBrush="Black" >
<RadioButton GroupName="main1" x:Name="radio1" Foreground="#FF030303" Background="#FF0075A9" />
</Border>
<Border Margin="20,0,20,0" Grid.Row="2" BorderThickness="2" BorderBrush="Black" >
<RadioButton GroupName="main1" x:Name="radio2" Foreground="#FF030303" Background="#FF0075A9" />
</Border>
....
so how to know which is checked ?
Upvotes: 0
Views: 2215
Reputation: 965
I think you may try something like that :
foreach (var radioButton in selective.Children.OfType<Border>().Select(b => b.Child).OfType<RadioButton>())
{
if (((RadioButton)radioButton).IsChecked ?? false)
{
//Do stuff
}
}
Here is how you get index and name of the RadioButton
:
var radioButtons = selective.Children.OfType<Border>().Select(b => b.Child).OfType<RadioButton>();
foreach (var radioButton in radioButtons)
{
if (radioButton.IsChecked ?? false)
{
var name = radioButton.Name;
var index = radioButtons.ToList().IndexOf(radioButton);
}
}
Upvotes: 2
Reputation: 5157
put main1
instead of this
for (int i = 0; i < main1.selective.Children.Count; i++)
{
if (main1.selective.Children[i].GetType().Name == "RadioButton")
{
RadioButton radio = (RadioButton)main1.selective.Children[i];
if ((bool)radio.IsChecked)
{
//get checked indes name
}
}
}
Upvotes: 0