Sss
Sss

Reputation: 1529

How to set radio.IsChecked = true; to a particular radiobutton programatically using c#

I am working on silverlight and i have created a radiobutton i want to set manually the check of radiobutton programatically to the given 3 items (itms means 3 radiobutton) on radio button.I tried like this

RadioButton radio = new RadioButton();

suppose this radio buttons contains " items( radio buttons) and when i try the code below to check the second item (out of 3 items) the code below checks the last item.

radio.Loaded += (p, q) =>
{       
       radio.IsChecked = true;
};

How i create button is :

foreach (String item in param.Component.Attributes[0].Item)
            {
                radio = new RadioButton()
                {
                    Content = item,
                    GroupName = "MyRadioButtonGroup",
                    Tag = tg

                };
 radio.Checked += (o, e) =>
                {
                    //Do  something                
                };

                sp.Children.Add(radio);
                count++; tg++;              
            }

Why checks the last item ? How to check the second item programatically usin silverlight in c# code? I try to do so because i want to intialise the radio button after the program launch (before button clicks) because on before button click of radio buttons if i try to print the itmes on text block, I see nothing (it only show on button clicks but i want something displayed before clicking instead of empty space)

Upvotes: 2

Views: 5842

Answers (1)

Walt Ritscher
Walt Ritscher

Reputation: 7037

The short answer to your question is that you set radio.IsChecked=truein the code to make the RadioButton checked.

One way to solve this is to set IsChecked = true when the second radio button is added. Since your code is in a foreach loop your count variable should work.

   foreach (String item in param.Component.Attributes[0].Item)
            {
                radio = new RadioButton()
                {
                    Content = item,
                    GroupName = "MyRadioButtonGroup",
                    Tag = tg

                };
 radio.Checked += (o, e) =>
                {
                    //Do  something                
                };

                sp.Children.Add(radio);
                count++; tg++;   
                if (count == 2){
                radio.IsChecked=true;
                }
            }

Or you could change your foreach loop to a for loop

for (int i = 0; i < param.Component.Attributes[0].Item.Count ; i++)
      {

      }


if (i== 2){
     radio.IsChecked=true;
   }

While both these approaches work they don't mesh well with the databound approach common in most Silverlight applications. The initial state of the selected items should really be stored in a state variable.

Upvotes: 2

Related Questions