简体   繁体   中英

How to get selected radio button in group via c#

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 ?

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
    }
}

Updated Answer

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);
    }
}

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
                   }
               }
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM